How to programmatically connect 2 android devices with bluetooth? - android

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?

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()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, request_code_for_enabling_bt);
}
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<BluetoothDevice> 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):
socket.connect();
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.

Related

Manually set bluetooth server port in Android

I have a working Bluetooth server running (Android app). I would like to set a specific Bluetooth port for it to listen to. The reason for that is that for the client to connect, it takes about 10-15 seconds because it needs to first discover the server (i do a scan ).
the code to create the server is the following:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
UUID my_uuid = UUID.fromString("12345678-f6ff-4f6f-1f1f-f8f8f8fffff8");
try {
BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord("myBluetoothServer", my_uuid);
sock1 = serverSocket.accept();
i_s = sock1.getInputStream();
o_s = new OutputStreamWriter(socket.getOutputStream());
new Thread(writter).start();
...
Question: how to specify a fixed port number for the server?
I have been looking here, of course, but it is not easy to find,:
https://developer.android.com/reference/android/bluetooth/BluetoothSocket?hl=ur
I am looking for something like serverSocket.setPort(myPortNumber) (pseudo - code)
The concept of port does not exist for Bluetooth Sockets since they are not regular TCP/IP sockets. They are just abstracted to behave like one.
As you figured out from your code, what you specify is a UUID which is a service identifier. The process to connect to a Bluetooth server goes like this:
Bluetooth Device scan: You can't skip this part, since you need a valid BluetoothDevice object
Service Discovery for a discovered Device: This is the part where you "check" if that Bluetooth Device is running the service that you are looking for (Your service UUID) So you shouldn't skip this part either, unless you want to connect to all surrounding Bluetooth devices.

Connect to specific Bluetooth device with a click

I'm trying to connect to a specific device using my Android APP, until now what I was able to do is get the paired items doing this :
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set < BluetoothDevice > pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device: pairedDevices) {
mDeviceName.add(device.getName());
mDeviceMAC.add(device.getAddress());
}
}
bluetoothClass.setDeviceName(mDeviceName);
bluetoothClass.setDeviceMac(mDeviceMAC);
Where I get the MAC and the Device name of all of my paired devices. The thing that I would like to do is when I select one it connects to the Bluetooth device.
EXAMPLE
On a Samsung S4 when I turn on the Bluetooth it popups a Dialog whitch contains all of my paired devices and when I click on anyone it connects (I've i'm able to ...) so basically I want to do this, since now I've been getting the paired devices (I don't know if it's the best way to get that but it does) and then when user click on anyone it connects to the device.
It's something like this question but it's unfortunately unanswered.
It's impossible to give you an example within this format, so I have provided you
with a good sample and helpful links to help you understand the sample.
I recommend you follow the steps I have provided and then, when you have
specific problems, you can bring it here, with the code snippet you are having
difficulty with.
I recommend you use download this sample code:
http://developer.android.com/samples/BluetoothChat/index.html
If you haven't already, it's good to study this:
http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html
This is a good tutorial and they have many tutorials:
http://www.tutorialspoint.com/android/android_bluetooth.htm
You will need the following permissions in your manifest:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
This is one intent that is advisable to use, to check to see if BT is enabled:
if (!mBluetoothAdapter.isEnabled()) {
android.content.Intent enableIntent = new android.content.Intent(
android.bluetooth.BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
and to make your device discoverable to other devices:
if (mBluetoothAdapter.getScanMode() !=
android.bluetooth.BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
android.content.Intent discoverableIntent =
new android.content.Intent(
android.bluetooth.BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
android.bluetooth.BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
300); // You are able to set how long it is discoverable.
startActivity(discoverableIntent);
}
As I mentioned in my answer here:
You can avoid using an intent to search for paired devices. When
connecting to a device that is not paired, a notification will pop up
asking to pair the devices. Once paired this message should not show
again for these devices, the connection should be automatic (according
to how you have written your program).
I use an intent to enable bluetooth, and to make my device
discoverable, I then set up my code to connect, and press a button to
connect. In your case, you will need to ensure your accessories are
discoverable also. In my case I use a unique UUID, and both devices
must recognise this to connect. This can only be used if you are
programming both devices, whether both are android or one android and
one other device type.
You will need to understand how to use sockets, this is how the devices communicate.
I recommend studying these two links:
http://developer.android.com/reference/android/bluetooth/BluetoothSocket.html
http://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html
Sockets are used to set up connections between devices. There will be a server socket and device sockets (determined by many factors, the programmer, the actual devices). The server socket listens for incoming connections, when a connection is accepted the devices connect, each with a simple socket.
I am not sure how much you know about threading.
The connection needs to be managed with threads:
http://developer.android.com/guide/components/processes-and-threads.html
http://android-developers.blogspot.com.au/2009/05/painless-threading.html
The connection between the devices is managed on threads separate from the User
Interface thread. This is to prevent the phone from locking up while it is
setting up, seeking and making a BT connection.
For instance:
AcceptThread - the thread that listens for a connection and accepts the connection (via the serversocket). This thread can run for an extended time waiting for a device to connect with.
ConnectThread - the thread that the device connecting to the server uses to connect to the serversocket.
ConnectedThread - this is the thread that manages the connection between both sockets.
Let me know if this helps you.

How do Bluetooth SDP and UUIDs work? (specifically for Android)

My understanding is that the SDP is a list of UUIDs that other devices can fetch.
According to this PDF from MIT, "A more general way to think of
SDP is as an information database." Does this mean I can add multiple values to SDP? Since Android has BluetoothDevice.fetchUuidsWithSdp(), how do I set the UUIDs of a device?
Also, what does each section of an UUID mean? UUIDs look like 00000000-0000-1000-8000-00805F9B34FB, but what information does this convey?
An UUID identifies a service that is available on a particular device. So if you call BluetoothDevice.fetchUUidsWithSdp() your BroadcastReceiver will receive the relevant Intent ACTION_UUID containing the device and the service UUID.
The bluetooth specification defines some common UUIDs.
If you don't want to connect to one of these well known services but intent to implement your own bluetooth application, then you have to just generate your own UUID (use uuidgen from a unix console or an online generator) that identifies your application/service.
You can create an UUID instance in java like this UUID uuid = UUID.fromString("785da8ea-1220-11e5-9493-1697f925ec7b");.
So if you create the server side for your bluetooth application on Android you typically do this
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothServerSocket serverSocket = adapter.listenUsingRfcommWithServiceRecord("YourHumanReadableServiceName", uuid);
And this is where you "set" your UUID. The Android bluetooth API creates the SDP-entry consisting of YOUR application's UUID and name for you. Other devices can now retrieve this entry. Androids bluetooth stack will now associate a bluetooth channel to your BluetoothServerSocket. If you want to connect to this ServerSocket, the connecting side usually connects doing this:
// you will most likely already have this instance from a discovery or paired device list
BluetoothDevice serverDevice = adapter.getRemoteDevice(bluetoothMacAddress);
// connect to your ServerSocket using the uuid
BluetoothSocket socket = serverDevice.createRfcommSocketToServiceRecord(uuid);
socket.connect();
Android will again do the heavy lifting for you: It checks the SDP-Records on the remote device, looks up the bluetooth channel that corresponds to your service's UUID and connects using this information.
There is a common code snippet spooking around here on SO that advices you to use "reflection" to get to a hidden API looking similar to this code:
try {
// this is the way to go
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect( );
} catch ( IOException exception ) {
// don't do that! You will bypass SDP and things will go sideways.
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
}
Most people try this and it "just works" in their dev environment but you should know what you do using this. You actively bypass the SDP lookup that retrieves the right bluetooth channel to be used with your service and you will end up connecting to channel 1. If you have more than one Service running on the device, things WILL go sideways in this cases and you will end up in debugging hell ;-)
I developed a small middleware called Blaubot to create small networks using bluetooth/wifi/nfc and experienced all sorts of problems on the devices I used to test with (12 models). It was often the case that the bluetooth stack was not fully functional anymore in cases where it got some load or after many connects/disconnects (which you usually will have, if you are developing your app). In these cases the device.createRfcommSocketToServiceRecord(uuid) would occasionally fail and only turning the bluetooth adapter off and on again helped to bring the bluetooth adapters back to life (in some cases only after a full power cycle). If this happens and you use the reflection method, you will probably not have much fun with bluetooth.
But if you know this and keep concurrent calls to the BluetoothAdapter within bounds, bluetooth connections and the adapters will be pretty stable.

How to connect ble device without scanning? Android 4.3

I try to develop a simple android app with a ble device.
I found many source code from the Intenet. However, both of them were start from scanning a list of available ble device.
As I have MAC address of the device,UUID of service and characteristic.
How can I connect to the known device and read one specific characteristic directly??
To connect a specific Bluetooth Device which has details like MAC address of the device, UUID of service and characteristic etc. you already know. To do this you need a BluetoothDevice object to make a call like this:
yourBluetoothDevice.connectGatt(getApplicationContext(), false, bleGattCallback);
So for this (yourBluetoothDevice) you have to start the scan at first to get same device object to connect by comparing it's MAC address. However, you got that same device object in onLeScan callback just stop scanning and make a connection with the same device.
Note: Making a connection should be on UIThread(Either using Handler, runOnUIThread or mainlooperThread) otherwise it will give issue in some devices for 'Fail to register callback'
Here yourBluetoothDevice is the device object reference with you want to make a connection.
bleGattCallback is the registered new BluetoothGattCallback() callback for connection status, discovered services, characteristics read and write etc.
Take a look at createInsecureRfcommSocketToServiceRecord. Something like this:
UUID uuid = UUID.fromString("<Your UUID>");
BluetoothSocket socket = yourBLEDevice.createInsecureRfcommSocketToServiceRecord(uuid);
Method m = yourBLEDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(yourBLEDevice, 1);
If you already know the mac address, you can try something like below:
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mMacAddress);
final BluetoothGatt mGatt = device.connectGatt(getApplication(), false, gattCallback);

Bluetooth socket

I am building tic tac to for two players and need a Bluetooth connection to exchange some data, I can enable Bluetooth, enable discover-ability but my problem in "BluetoothServerSocket" and the client "BluetoothSocket", I don't know how to manipulate this part,
this is the code:
ArrayList<String>al=new ArrayList<String>();
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = ba.getBondedDevices();
if(pairedDevices.size()>0)
for(BluetoothDevice d: pairedDevices)
al.add(d.getName()+" , "+d.getAddress());
if (!ba.isEnabled())
ba.enable();
BluetoothDevice device;
Intent dis=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dis.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(dis);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID);
socket.connect();
InputStream is=socket.getInputStream();
OutputStream os=socket.getOutputStream();
Both the players will communicate over 'BluetoothSocket's using which you can send/receive data using InputStreams and OutputStreams. But for getting such a pair of sockets you can do this thing :
Create BluetoothServerSocket on the side of one player and other one connects to it. The BluetoothServerSocket listens for connections using the 'accept' method which blocks till a client BluetoothSocket connects to it. After that the BluetoothServerSocket.accept() method returns a BluetoothSocket which can be used with the client Btsocket for 2-way info transfer.
Hope this helps...
PS: createRfcommSocketToServiceRecord just creates one such client mentioned above. You may use the same UUID for both sides
It seems you're missing a lot of complexity regarding data exchange. Mainly you'll need to deal with threads to listen/send data. Here you have a complete implementation of what I'm talking about: https://github.com/buddles/AndBT/blob/master/AndBT/src/br/pucrs/tcii/BluetoothService.java
Have you considered to use an already implemented library? This project comes with a TicTacToe sample and a Chat app that supports up to seven connections: https://github.com/buddles/AndBT
You may refer this link. This is a simple bluetooth chat app. You can modify this app to send and receive the required data.

Categories

Resources