Android Connect Bluetooth Device Automatically After Pairing Programmatically
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 btDe
Solution 1:
I found the solution.
First I need a BroadcastReceiver
like:
privateBroadcastReceivermyReceiver=newBroadcastReceiver() {
@OverridepublicvoidonReceive(Context context, Intent intent) {
Stringaction= intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevicedevice= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
// CONNECT
}
} elseif (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevicedevice= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Discover new device
}
}
};
And then I need register the receiver as follow:
IntentFilterintentFilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
context.registerReceiver(myReceiver, intentFilter);
In this way the receiver is listening for ACTION_FOUND
(Discover new device) and ACTION_BOND_STATE_CHANGED
(Device change its bond state), then I check if the new state is BOND_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 and device.getBondState() == BluetoothDevice.BOND_BONDED
will be True
and it will connect.
Post a Comment for "Android Connect Bluetooth Device Automatically After Pairing Programmatically"