Android bluetooth connected but not paired

Bluetooth paired but not connected android

I’ve been doing some stuff around this lately and I’ve used the following code, which has worked fine for me: For prompting the user to select which device, you can query the BluetoothAdapter for all the currently paired devices as follows: Finally, it is possible to create connections to multiple devices at the same time — have a look here: Android Bluetooth API connect to multiple devices Devices that I’m having problems with connecting these devices: Htc one(android 4.2)

Bluetooth paired devices connection problems

I’m having issues with connecting. At first it works, than it does not, unless I unpair the devices. I’ve gotten every possible exception that could happen, socket closed, pipe closed, connection refused, port already in use, etc.

I’m aware that there are issues with bluetooth on android pre 4.2 (https://code.google.com/p/android/issues/detail?id=37725).

Devices that I’m having problems with connecting these devices:

Another minor issue is, that the paired devices are not stored (mostly on the nexus 4, and the sgs2).

private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //this is the other one that I've tried: fa87c0d0-afac-11de-8a39-0800200c9a66"); private static final String NAME = "BluetoothConnector"; public void listenForConnection() throws IOException, BluetoothException < //first close the socket if it is open closeSocket(); BluetoothServerSocket mServerSocket = null; try < mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID_SECURE); //ioexception here! >catch (IOException e) < if (Build.VERSION.SDK_INT >= 9) < try < //this is a stupid hack, http://stackoverflow.com/questions/6480480/rfcomm-connection-between-two-android-devices Method m = mBluetoothAdapter.getClass().getMethod("listenUsingRfcommOn", new Class[] < int.class >); mServerSocket = (BluetoothServerSocket) m.invoke(mBluetoothAdapter, PORT); > catch (Exception ex) < Log.e(ex); throw e; >> else < throw e; >> while (!isCancelled) < try < socket = mServerSocket.accept(); >catch (IOException e) < if (socket != null) < try < socket.close(); >finally < socket = null; >> throw e; > if (socket == null) < throw new BluetoothException("Socket connection connected, but null"); >else < isConnected = true; break; // everything is ok >> > public void connect(String address) throws IOException, BluetoothException < mBluetoothAdapter.cancelDiscovery(); BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); try < socket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE); >catch (IOException e1) < Log.e(e1); if (Build.VERSION.SDK_INT >= 9) < try < Method m = device.getClass().getMethod("createRfcommSocket", new Class[] < int.class >); socket = (BluetoothSocket) m.invoke(device, PORT); > catch (Exception e) < Log.e(e); throw e1; >> else < throw e1; >> // Make a connection to the BluetoothSocket try < // This is a blocking call and will only return on a // successful connection or an exception socket.connect(); >catch (IOException e) < Log.e(e); // Close the socket try < socket.close(); >catch (IOException e2) < Log.e(e2); Log.wtf("unable to close() socket during connection failure"); >throw e; > 
private void closeSocket() < try < if (socket != null) < socket.close(); socket = null; Log.d("Socket closed"); >> catch (IOException e) < Log.e(e); Log.wtf("close() of connect socket failed"); >> 

I tried changing the uuid(random one also), tried looking at older sdk samples. So what could be wrong here?

edit: trying to clarify: the problem usually comes up, when 2 devices that have been paired, connected, did some successful communication, get disconnected (by the user). After that, they can not be reconnected, unless they get rebooted, or unpaired manually.

You are trying to paired this manner:

private void TwitPairedDevice() < buttonTwitPairDevice.setOnClickListener(new OnClickListener() < @Override public void onClick(View v) < SetfetchPairedDevices=bluetooth.getBondedDevices(); Iterator iterator=fetchPairedDevices.iterator(); while(iterator.hasNext()) < final BluetoothDevice pairBthDevice=iterator.next(); final String addressPairedDevice=pairBthDevice.getAddress(); AsyncTaskasynchPairDevice=new AsyncTask() < @Override protected Void doInBackground(Integer. params) < try < socket=pairBthDevice.createRfcommSocketToServiceRecord(uuid); socket.connect(); >catch (IOException e) < e.printStackTrace(); >return null; > > >;asynchPairDevice.execute(); > > >); > 
 private void FetchPairedDevices() < SetpairedDevices=bluetooth.getBondedDevices(); for(BluetoothDevice pairedBthDevice:pairedDevices) < listPairedDevice.add(pairedBthDevice.getName()); >listviewPairedDevice.setAdapter(adapterPairedDevice); listviewPairedDevice.setOnItemClickListener(new OnItemClickListener() < @Override public void onItemClick(AdapterViewarg0, View arg1, int arg2, long arg3) < Object listPairedName=arg0.getItemAtPosition(arg2); String selectedPairedName=listPairedName.toString(); SetbthDeviceChecking=bluetooth.getBondedDevices(); for(final BluetoothDevice bthDevice:bthDeviceChecking) < if(bthDevice.getName().contains(selectedPairedName)) < listPairDevice.clear(); listPairDevice.add(bthDevice); final String addressPairedDevice=bthDevice.getAddress(); AsyncTaskasynTask=new AsyncTask() < @Override protected Void doInBackground(Integer. params) < try < socket=bthDevice.createRfcommSocketToServiceRecord(uuid); socket.connect(); >catch (IOException e) < e.printStackTrace(); >return null; > >; asynTask.execute(arg2); > > > >); > 

It seems that at this point Bluetooth is broken on android.

Читайте также:  Emachines e525 есть ли блютуз

There is no sure way of connecting 2 devices, that works all the time. Some people are using an unofficial way to do it, but that does not work on all devices.

I did some in house testing, with the top 10 devices, that are on the market currently, so after around around 90 test runs, the hacked method worked 75% of the time, which is not good enough.

For example, the htc oneX will just handle incoming Bluetooth request, as a Bluetooth hands free device(it is connecting succesfully!), but makes messaging impossible.

After implementing full Bluetooth functionality, we decided to remove it from our app, and release it without it. We’ll switch to wifi in some later release.

Android — Bluetooth paired devices connection problems, It seems that at this point Bluetooth is broken on android. There is no sure way of connecting 2 devices, that works all the time. Some people are using an unofficial way to do it, but that does not work on all devices.. I did some in house testing, with the top 10 devices, that are on the market currently, so after around …

How to FIX Bluetooth on Android Phone that FAILS to

Hi, this video shows you a simple FIX to get your Bluetooth working again on your Android mobile cell phone. It also shows you another option using a plug in

Android Bluetooth Fails to Pair

I am having a problem getting my devices to pair in Android. If I go into the settings and pair them manually I can get them to connect using the following code:

@Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.connect); Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(discoverableIntent, REQUEST_ENABLE_BT); >@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) < if(requestCode == REQUEST_ENABLE_BT) < if(resultCode == RESULT_CANCELED) < new AlertDialog.Builder(this) .setTitle(R.string.error) .setMessage(R.string.bluetooth_unavailable) .setPositiveButton(android.R.string.ok, AndroidUtils.DismissListener) .create() .show(); >else < mServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("Moo Productions Bluetooth Server", mUUID); mState = State.ACCEPTING; BluetoothSocket socket = mServerSocket.accept(); mServerSocket.close(); connected(socket); >> > 
Set pairedDevices = mAdapter.getBondedDevices(); BluetoothSocket socket = null; // Search the list of paired devices for the right one for(BluetoothDevice device : pairedDevices) < try < mState = State.SEARCHING; socket = device.createRfcommSocketToServiceRecord(mUUID); mState = State.CONNECTING; socket.connect(); connected(socket); break; >catch (IOException e) < socket = null; continue; >> 

But if the devices hadn’t already been paired it gets out of the foreach without connecting to a valid socket. In that case I start discovering.

// If that didn't work, discover if(socket == null) < mState = State.SEARCHING; mReceiver = new SocketReceiver(); mContext.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); mAdapter.startDiscovery(); >// . Later . private class SocketReceiver extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) < try < // Get the device and try to open a socket BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(mUUID); mState = State.CONNECTING; socket.connect(); // This is our boy, so stop looking mAdapter.cancelDiscovery(); mContext.unregisterReceiver(mReceiver); connected(socket); >catch (IOException ioe) < ioe.printStackTrace(); >> > > 

But it will never find the other device. I never get a pairing dialog and when I step through I see that it discovers the correct device, but it fails to connect with this exception java.io.IOException: Service discovery failed . Any ideas as to what I’m missing?

Читайте также:  Windows 10 aac bluetooth включить

Your client will never discover the server if the server is not actually discoverable. Your server code’s comment says «Make sure the device it discoverable,» but listening on a socket does not mean the device is discoverable. You can make the server discoverable by calling:

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent); 

This is an Intent because discoverability must be enabled by the system and only with approval from the user (so this will raise a dialog, requesting discoverability for 300 seconds). Only during this window of 300 seconds will the server actually be discoverable. During this time, your client code should work just fine and you’ll get the pairing requests.

This is all covered in detail in the Android dev guide: http://developer.android.com/guide/topics/wireless/bluetooth.html

Don’t know if it’s still relevant, but I did it like this and it worked:

if (BluetoothDevice.ACTION_FOUND.equals(action)) < discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); >if (discoveredDeviceName.equals("your_device_name"))

Also, I would try to cancel discovery before:

BluetoothSocket socket = device.createRfcommSocketToServiceRecord(mUUID); socket.connect(); 

Android — Bluetooth not getting paired, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Connecting to a already paired Bluetooth device

Recently I tried to get a pairing process to work programatically and I succeded. But I recently found out that the users of my application can be connected to several of «interesting» devices. So I have to prompt the user to choose a device to connect to

So I have to connect the user to a already paired bluetooth device. But none of my efforts work. I tried running the pairing process again using the:

Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] ); mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1); 

which is the one I’ve implemented and the only working way to pair my phone with my embedded bluetooth device

So my question is:

  • Is it possible for me to disconnect a paired device and then connect to another embedded device? I tried.. to simply connect to the new device but I can’t get that to work

I’m afraid I’m not entirely sure what your problem is. Is it that you are unable to create a socket to an already paired bluetooth device?

First of all, if the device is already paired, you don’t need to run the pairing process again. You just need to create the socket for communication, which will fail if the device is not available to communicate with. I’ve been doing some stuff around this lately and I’ve used the following code, which has worked fine for me:

 try < Method m = device.getClass().getMethod("createRfcommSocket", new Class[] < int.class >); BluetoothSocket mySocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1)); > catch () < //Do stuff >

For prompting the user to select which device, you can query the BluetoothAdapter for all the currently paired devices as follows:

Set bondedDevices = BluetoothAdapter .getDefaultAdapter().getBondedDevices(); 

Finally, it is possible to create connections to multiple devices at the same time — have a look here: Android Bluetooth API connect to multiple devices

PC and Android phone Bluetooth connection keeps, I can get them to pair, and even connected but every time after a few seconds, the Connected drops to Paired. Both devices connect and stay connected to other devices, mouse, headphones, speakers etc. But not the PC to the Phone. Would like to be actually use the Bluetooth method of connection both for …

Читайте также:  Блютуз наушники запаздывает звук

Источник

Как исправить проблемы с сопряжением по Bluetooth

Соединение по Bluetooth — хороший способ перекинуть файлы с одного устройства на другое или подключить беспроводные гаджеты друг к другу. Но иногда возникают проблемы с сопряжением. Рассказываем, что делать, если подключение по Bluetooth не работает.

В целом, Bluetooth имеет обратную совместимость: устройства, поддерживающие стандарт Bluetooth 5.0, по-прежнему могут сопрягаться с устройствами, использующими, скажем, древний Bluetooth 2.1, вышедший еще в 2007 году.

Исключение составляют гаджеты, которые используют версию с низким энергопотреблением под названием Bluetooth Low Energy, которая работает по другому протоколу, нежели старые или «классические» устройства Bluetooth. Устройства с BLE не обладают обратной совместимостью и не распознают старые устройства, поддерживающие классический Bluetooth. Обычно BLE-девайсы — это метки, фитнес-браслеты и пр.

Если устройство поддерживает Bluetooth 4.0, 4.2 или 5.0, оно должно распознавать в том числе и Bluetooth LE

Что можно сделать, если соединение по Bluetooth не работает?

1. Убедиться, что Bluetooth активен, а устройства сопряжены и находятся на близком расстоянии друг от друга. Иногда для сопряжения требуется ввести код в смартфоне или ПК.

2. Включить режим видимости. Часто это касается фитнес-браслетов и информационно-развлекательной системы автомобиля — пользователи забывают активировать режим видимости.

3. Выключить и снова включить оба устройства либо соединение Bluetooth — как ни странно, но это до сих пор один из самых работающих методов.

4. Удалить старые подключения. Иногда гаджеты поддерживают только одно подключение — особенно часто это касается беспроводных колонок. Так что вы можете пытаться подключить динамик к планшету, в то время как он успешно сопрягается с устройством, с которым соединился в последний раз, например, со смартфоном. Выключите на время этот девайс или удалите у него подключение.

5. Зарядить оба устройства, которые пытаетесь связать. Некоторые гаджеты поддерживают интеллектуальное управление питанием, которое может отключать Bluetooth, если уровень заряда батареи слишком низкий.

6. Удалить устройство со смартфона и найти заново. В настройках iOS вы можете удалить устройство, нажав на его имя, а затем «Забыть это устройство». На Android коснитесь имени устройства и затем «Разорвите пару». Если речь идет о системе автомобиля, может потребоваться выключить зажигание, открыть и закрыть дверь авто и подождать пару минут, прежде чем пытаться снова выполнить сопряжение.

7. Отойти от источников помех. Очень редко, но могут мешать сигналы от других устройств, например, Wi-Fi-роутера, порта USB 3.0. Помехой может стать даже усиленный чехол для смартфона.

8. Обновить драйверы и прошивку оборудования.

9. Очистить кэш Bluetooth. Иногда приложения могут мешать работе Bluetooth и очистка кэша может решить проблему. В Android-устройствах этот раздел находится в настройках системы: «Система» — «Дополнительно» — «Сбросить параметры» — «Сбросить настройки Wi-Fi, мобильного телефона и Bluetooth». На iOS понадобится разорвать пару со всеми устройствами (перейдите в «Настройки» — Bluetooth, выберите значок информации и «Забыть это устройство» для каждого девайса), затем перезагрузить гаджет.

Данный материал является частной записью члена сообщества Club.CNews.
Редакция CNews не несет ответственности за его содержание.

Источник

Оцените статью
Adblock
detector