How to programmatically connect 2 android devices with bluetooth?
I am developing an application which should connect 2 Android devices through Bluetooth automatically. Let’s say they are already paired. Is it possible to achieve that?
On the downside, such an application, e.g. that is constantly paging to make a connection, will adversely affect the battery life. Not a good idea.
1 Answer 1
Of course it is possible. I’ll make a short tutorial out of the documentation:
Start with the BluetoothAdapter — it is your Bluetooth manager.
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
If bluetoothAdapter is null, it means that this Android device does not support Bluetooth (It has no Bluetooth radio. Though I think it’s rare to encounter these devices. )
Next, make sure Bluetooth is on:
if (!bluetoothAdapter.isEnabled())
If it’s not on, we start the activity which asks the user to enable it.
Let’s say the user did enable (I guess you should check if he did, do it in your onActivityResult method). We can query for the paired devices:
Set pairedDevices = bluetoothAdapter.getBondedDevices();
Then loop over them: for(BluetoothDevice device : pairedDevices) and find the one you want to connect to.
Once you have found a device, create a socket to connect it:
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(YOUR_UUID);
YOUR_UUID is a UUID object containing a special ID of your app. Read about it here.
Now, attempt to connect (The device you are trying to connect to must have a socket created with the same UUID on listening mode):
connect() blocks your thread until a connection is established, or an error occurs — an exception will be thrown in this case. So you should call connect on a separate thread.
And there! You are connected to another device. Now get the input and output streams:
InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream();
and you can begin sending/receiving data. Keep in mind that both actions (sending and receiving) are blocking so you should call these from separate threads.
Read more about this, and find out how to create the server (Here we’ve created a client) in the Bluetooth documentation.
Подключение Android-смартфонов по Bluetooth
По умолчанию функциональность соединения двух Андроид-телефонов невелика – по сути, можно только обмениваться файлами или использовать в комплексе с Wi-Fi и/или NFC для специальных технологий передачи данных (например, HuaweiShare или ShareMe), поэтому покажем процесс соединения именно на примере пересылки документа.
- Первым делом активируйте функцию беспроводной связи – в большинстве современных смартфонов сделать это можно через центр уведомлений. Альтернативный вариант – вызвать «Настройки», затем перейти к беспроводным соединениям, найти в перечне пункт «Bluetooth» и активировать нужный переключатель уже оттуда. Повторите эти же действия для смартфона, к которому нужно подключиться.
Как видим, ничего сложного нет. В дальнейшем, когда устройство будет внесено в перечень сопряжённых, к нему для передачи можно будет подключаться одним тапом.
Bluetooth data transfer between two Android devices
I have been following this Android guide for Bluetooth communication To explain exactly what I want to do, when the two devices are paired, two different activities open up on each device (server and client) where on the server activity I have different buttons, and on the client activity there is just a textview. I want to be able to press a button on the server device and display it on the client. I have managed to establish a connection between the two devices, but now I want to send data which I have not been able to do. They give this code for data transfer:
private class ConnectedThread extends Thread < private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) < mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams, using temp objects because // member streams are final try < tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); >catch (IOException e) < >mmInStream = tmpIn; mmOutStream = tmpOut; > public void run() < byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) < try < // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); >catch (IOException e) < break; >> > /* Call this from the main activity to send data to the remote device */ public void write(byte[] bytes) < try < mmOutStream.write(bytes); >catch (IOException e) < >> /* Call this from the main activity to shutdown the connection */ public void cancel() < try < mmSocket.close(); >catch (IOException e) < >> >
// Send the obtained bytes to the UI activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
And is not explained in the guide. I don’t know what the mHandler is or does. Apart from the error, I don’t even really understand where to put this code. Should it be in the second activities (server and client) that I open or in the main? If in the Server activity, should it be in the onClick method for all the buttons with a different byte code to send for each button? And in this code, how do we distinguish who is sending and who is receiving?
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.