In my app I need pairing bluetooth device and immediately connect with it.
I have the following function in order to pairing devices:
public boolean createBond(BluetoothDevice btDevice)
{
try {
Log.d("pairDevice()", "Start Pairing...");
Method m = btDevice.getClass().getMethod("createBond", (Class[]) null);
Boolean returnValue = (Boolean) m.invoke(btDevice, (Object[]) null);
Log.d("pairDevice()", "Pairing finished.");
return returnValue;
} catch (Exception e) {
Log.e("pairDevice()", e.getMessage());
}
return false;
}
And I use it as the following way:
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//Connect with device
}
}
And it show me the dialog to pairing devices and enter the pin.
The problem is that createBond functions always return true, and it doen's wait until I enter the pin and paired with device, so I don't use correctly:
isBonded = createBond(bdDevice);
if(isBonded) {...}
So the question is How can I paired with device and when it is paired connect to it?
P.D My code is based in the first answer of the following thread: Android + Pair devices via bluetooth programmatically
Best Answer
I found the solution.
First I need a
BroadcastReceiver
like:And then I need register the receiver as follow:
In this way the receiver is listening for
ACTION_FOUND
(Discover new device) andACTION_BOND_STATE_CHANGED
(Device change its bond state), then I check if the new state isBOND_BOUNDED
and if it is I connect with device.Now when I call
createBond
Method (described in the question) and enter the pin,ACTION_BOND_STATE_CHANGED
will fire anddevice.getBondState() == BluetoothDevice.BOND_BONDED
will beTrue
and it will connect.