Switch bluetooth device android

Programmatically connect to paired Bluetooth device

Is there a way, using the Android SDK, to programmatically connect to an already-paired Bluetooth device? In other words: I can go into Settings -> Wireless & networks -> Bluetooth settings, and tap the device (listed as «Paired but not connected»), at which point it will connect. I’d like to be able to do this programmatically, but don’t see a way to do this. I see the options to create an RFCOMM socket, and for a SPP device, I’m assuming that’ll do the connection part as well, but for an A2DP device, where the actual data transfer will be handled by the OS rather than by my app, I think that’s not applicable?

4 Answers 4

Okay, since this was driving me crazy, I did some digging into the source code and I’ve found a 100% reliable (at least on my Nexus 4, Android 4.3) solution to connect to a paired A2DP device (such as a headset or Bluetooth audio device). I’ve published a fully working sample project (easily built with Android Studio) that you can find here on Github.

Essentially, what you need to do is:

  • Get an instance of the BluetoothAdapter
  • Using this instance, get a profile proxy for A2DP:

adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);

where listener is a ServiceListener that will receive a BluetoothProfile in its onServiceConnected() callback (which can be cast to a BluetoothA2dp instance)

Method connect = BluetoothA2dp.class.getDeclaredMethod(«connect», BluetoothDevice.class);

String deviceName = "My_Device_Name"; BluetoothDevice result = null; Set devices = adapter.getBondedDevices(); if (devices != null) < for (BluetoothDevice device : devices) < if (deviceName.equals(device.getName())) < result = device; break; >> > 

Which, at least for me, caused an immediate connection of the device.

Источник

Android: Switch between SPP Bluetooth Devices

I have two different Bluetooth Printers. Bixolon SPP-R200 and Fujitsu FTP-628WSL110. I can connect to each of them separately (using a Samsung Galaxy SII) print, disconnect and reconnect just fine. However, if I switch off the Bixolon and try to pair with the Fujitsu (previously unpaired, Bixolon is still paired), then it fails when trying to connect to the created socket. Same the other way around. Here is the error message:

07-02 13:00:11.040: E/MyApp.BluetoothConnection(9380): Failed to connect to rfcomm socket. 07-02 13:00:11.040: E/MyApp.BluetoothConnection(9380): java.io.IOException: Service discovery failed 07-02 13:00:11.040: E/MyApp.BluetoothConnection(9380): at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:406) 07-02 13:00:11.040: E/MyApp.BluetoothConnection(9380): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:217) 07-02 13:00:11.040: E/MyApp.BluetoothConnection(9380): at MyApp.BluetoothConnection.connect(BluetoothConnection.java:171) 07-02 13:00:11.040: E/MyApp.BluetoothConnection(9380): at MyApp.AbstractBluetoothPrinter.connect(AbstractBluetoothPrinter.java:34) 

Here is the code, which makes the connection attempt, the line that fails under the explained circumstances is btSocket.connect(); — exception see above:

/** Is set in connect() */ private BluetoothSocket btSocket = null; /** Is set prior to connect() */ private BluetoothSocket btDevice; public boolean connect() < try < btSocket = btDevice.createRfcommSocketToServiceRecord("00001101-0000-1000-8000-00805F9B34FB"); if (btDevice.getName().startsWith("FTP")) < //Special treatment for the fujitsu printer SystemClock.sleep(1000); >> catch (Throwable e) < LogCat.e(TAG, "Failed to create rfcomm socket.", e); return false; >try < // Stop Bluetooth discovery if it's going on BluetoothHandler.cancelDiscovery(); // This fails under the described circumstances btSocket.connect(); >catch (Throwable e) < LogCat.e(TAG, "Failed to connect to rfcomm socket.", e); return false; >// Obtain streams etc. > 

I am using the same UUID to connect to both devices (but only one device is switched on at a time, they’re never switched on at the same time), the well known SPP UUID from the SDK API:

00001101-0000-1000-8000-00805F9B34FB 

Which makes me wonder: Could it be, that I need a different UUID for each device? If yes any idea which?

Читайте также:  Nissan consult can bluetooth

1 Answer 1

Ok after several days of trying different solutions, I am now able to switch between the afore mentioned printers. Since I am not entirely sure which of my measures was the reason for succeeding, I’ll list them all, so someone stumbling upon this post will have some clues on how to fix his bluetooth issues. One thing however I am quite sure about: You don’t need different UUIDs to connect two different printers — you can use the same UUID (But I only ever have one of them switched on).

I cache the device that was last printed to — however unlike before I no longer cache the actual BluetoothDevice, instead I only cache it’s mac address which is obtainable through:

BluetoothDevice bluetoothDevice; //Obtain BluetoothDevice by looking through paired devices or starting discovery bluetoothDevice.getAddress(); 

getAddress() returns a String: The hardware address of the device. I cache that mac address and next time the user wants to print, I match the cached mac address against the mac addresses of all paired printers — if the mac address matches one of these, I try to connect to that printer. If that fails, I reset my cached mac address and try to find another device by first checking my paired devices if one of them can connect (if I can successfully connect I update my cached mac address accordingly), and if that fails I start a bluetooth discovery looking for other potential devices.

Now in order to not leave any socket connections open to one of my printers my routine is as follows (I’ll leave out the try-catches I have wrapped around each call to ease the read):

Create the socket

BluetoothSocket btSocket = btDevice.createRfcommSocketToServiceRecord(MY_UUID); 

The MY_UUID refers to the well known UUID used for connecting to SPP devices:

00001101-0000-1000-8000-00805F9B34FB 

If the socket creation fails (which is rare and if it happens it’s most likely due to insufficient permissions or bluetooth being disabled/not available), we can’t proceed further, as we need a socket to connect to. Hence, in your catch block you should trigger the disconnect method (more on that later).

Connect to the created socket

If the connect fails, we can’t proceed further, as we need a valid socket connection to obtain the input and output streams. Hence, in your catch block you should trigger the disconnect method (more on that later).

Obtain the input and output stream

The next step would be to obtain the input and output streams from the socket. I do this in a for loop which runs a couple of times (5 times should be enough) — in each iteration I check if I have the output stream, if not, I try to obtain it, same for the input stream. At the end of the loop I check if I have both my streams, if yes I exit the loop (AND the whole connect method), if no, I proceed with the loop and try again. Usually I get both my streams in the first loop-iteration, however sometimes I need two or three iterations to obtain both streams.

Читайте также:  Bluetooth headset flashing red

If I reach the code that follows after the loop declaration I obviously did not get my streams or something else went wrong. At this point the connect is considered to have failed and I execute my disconnect code (which cleans up open streams & sockets, more on that later).

Now that you have a connection to your target bluetooth device you can perform read and write operations. Once you’re done you should cleanup by closing all streams and sockets, more on this in the next paragraph: Disconnecting. Remember: If an exception occurs during read/write operations, be sure to trigger the disconnect method in order to cleanup your resources. If your printer needs some kind of initialization command, be sure to send that right after connecting to the printer and before performing your read/write operations.

Disconnecting

There are usually two occasions on which you should disconnect:

  • Once you’re done with your read/write operations
  • If an exception occurred somewhere along the way, to cleanup your resources

Close your streams

The first thing you want to do is cleanup your streams, check both, your input and output stream, if they’re not null, close them and set them to null. Be sure to wrap each operation (closing the input stream, closing the output stream etc. ) into its own try-catch as otherwise failing to do one cleanup (Because an exception is raised) will skip all other cleanup measures.

Close the socket

Now that you’ve made sure your input streams are cleaned up, proceed to closing your socket connection and setting it to null thereafter.

One more thing: I have a Thread.sleep at the beginning and end of my disconnect method. The one in the beginning is about 2.5 seconds (= 2500 milliseconds) long, the purpose is to make sure nothing else is going on with the printer (such as pending read/write operations or the printer still printing etc..). The second Thread.sleep is at the end of my disconnect method and is about 800 milliseconds long. The reason for that sleep at the end is related to the problems I had when trying to immediately open a new socket right after closing one. For more details please refer to this answer.

In case anyone has questions related to my OP or my answer, please let me know in the comments and I’ll try my best to answer them.

Источник

Переключения между Bluetooth-устройствами в Android одним нажатием: настраиваем

Так что, если вам, дорогой читатель, её тоже не хватает, то зашли вы по адресу. Сейчас расскажем, как сделать почти такую же. И даже лучше.

Читайте также:  Отправить файлы компьютера телефон bluetooth

как настроить функцию быстрого переключения между Bluetooth-устройствами в Android

Значит, прога, а точнее виджет или, если еще точнее, то Bluetooth Audio Device Widget (это официальное название), предназначена как раз для того, чтобы упростить и ускорить процесс переключения между Bluetooth-аксессуарами на любом совместимом смартфоне или планшете.

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

#1 — качаем и устанавливаем Bluetooth Audio Device Widget
#2 — даем необходимые разрешения

По факту установки прога затребует разрешение на доступ к данным о местоположении. НО данные эти требуются только для работы с наушниками Apple AirPods.

Так что, если таковые в списке подключенных имеются, то тогда тапаем вариант «Разрешить всегда» (или «Разрешить однократно»), это во-первых.

Переключения между Bluetooth-устройствами в Android одним нажатием: настраиваем

Во-вторых, приложение также спросит разрешение работать в фоновом режиме. По идее, так оно должно должно функционировать быстрее и экономнее.

Потому если хотим разрешить, то идем в «Настройки«, далее — в раздел «Батарея«, там открываем «Контроль активности«, в списке приложений тапаем «Bluetooth Audio Widget» и ставим ему режим «Без ограничений«.

#3 — настраиваем сам виджет

После установки приложение само находит все совместимые Bluetooth-устройства (в том числе и те, которые к смартфону подключались когда-то) и для каждого можно выбрать отдельный значок.

Для этого открываем приложение, в списке тапаем по названию Bluetooth-девайса, жмем «Изменить значок» и выбираем подходящий, по которому и будем узнавать устройство в виджете на главном экране.

Попутно можно активировать также «Плитку быстрых настроек» и опции быстрого запуска приложение, скрытия названия устройства в виджете и автоматического отключения Bluetooth смартфона при выключении устройства.

И что еще интереснее, в «Настройках» виджета есть пункт «Громкость«. В нём можно заранее установить уровень громкости по умолчанию для каждого устройств, плюс установить плеер (или несколько), который будет автоматом запускаться при нажатии значка соответствующего устройства в виджете.

#4 — добавляем виджет на домашний экран
  • переходим на домашний экран смартфона;
  • тапаем по пустому месту и держим нажатие, пока откроется доп-меню, в нем жмем кнопку «Виджеты«;
  • в списке виджетов находим «Bluetooth Audio Widget«, жмем и просто перетаскиваем значок, куда надо и отпускаем;
  • приложение тут же предложит назначить на этому значку его Bluetooth-устройство — выбираем, назначаем;
  • после этого повторяем то же самое для всех прочих Bluetooth-устройств, для которых надо настроить быстрое переключение;
  • и расставляем значки в удобном порядке.

Переключения между Bluetooth-устройствами в Android одним нажатием: настраиваем

#5 — как переключаться между Bluetooth-устройствами в Android одним нажатием?

Ну вот теперь одним тапом по значку и переключаемся. То есть, просто жмем значок девайса — и смартфон тут же к нему подключается (если устройство находится в пределах досягаемости Bluetooth-модуля, конечно).

Когда надо быстро переключиться на друге устройство, жмем его значок в виджете — полсекунды и смартфон его нашел и подключился. Вот и вё.

Источник

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