How to disconnect bluetooth in android - android

I am trying to disconnect bluetooth by using
if (bluetoothAdapter != null) {
if(bluetoothAdapter.isEnabled()|bluetoothAdapter.isDiscovering()){
bluetoothAdapter.disable();
bluetoothAdapter.cancelDiscovery();
}
}
But it is not working.Can anyone suggest something on that which will be fruitful for me.

If you are disconnecting you should try and disconnect your specific connection rather than turning off bluetooth.. turning off will cause other active connections (which you might not have created also to disconnect)
If this is what you want i.e to disconnect every thing, then in the code above you should first cancel Discovery then Disable.
To do both of these you need the BLUETOOTH_ADMIN privilege.

Related

Bluetooth LE disconnect() - Android behavior

I have a question about Android bluetooth LE disconnect(), which behaves differently, depending on the running scenario.
My application connects to an embedded device which runs the GATT server and the communication is working fine. The device is not bonded, pairing process happens every time i connect to it and i disconnect every time the Android activity is closed or paused.
protected void onPause(){
super.onPause();
if(mGattUpdateReceiver != null)
unregisterReceiver(mGattUpdateReceiver);
if (mBluetoothLeService != null)
mBluetoothLeService.disconnect();
}
If the connection is idle (no communication forth and back) then disconnect() works fine and i can see the device receiving disconnect event and everything good.
But when i run a timer on the device sending indications with counting value to android every 750 msec, no disconnect happens when the activity is paused/closed. The device keep sending the counter value and receives HVC confirmations for ever. The only way to stop Android to send HVCs is to disable BT adapter on the phone. Killing the application doesn't help.
I saw this answer here stackoverflow.com/questions/44521828/android-ble-gatt-disconnected-vs-device-disconnected
which is 4 years old. Are we in the same situation now or did I mess it somehow?
Good point!
Yes on a second device it works as expected. As soon as onPause() is hit disconnect is triggered to the remote device, no matter if communication is ongoing or not.
So nothing wrong with Android but something wrong with BT stack on my first device (SGS8)

calling connectGatt() and createBond() together

I'm trying to create a bond between my Android phone and my device. Before they were connected well by calling device.connectGatt() with my gattCallback. But now as I want to also want to add bonding by calling device.createBond(), my onConnectionStateChange shows an alternate pattern of connected and disconnected with the status code 0 when connected and 8 when disconnected. Here is my snippet of code of how I'm trying to use connectGatt and createBond together.
#Override
public void onScanResult(int callbackType, ScanResult result) {
System.out.println("on scan result");
super.onScanResult(callbackType, result);
BluetoothDevice device = result.getDevice();
synchronized (this) {
if (mBluetoothGatt == null) {
if (device.createBond()) {
System.out.println("create bond success");
mBluetoothGatt = device.connectGatt(mListener.retrieveApplicationContext(), true, mGattCallback);
}
else System.out.println("create bond sb");
}
}
}
Is there anything wrong by calling these two methods in this way? I searched the internet for creating bonds but none of the pages uses createBond and connectGatt together. I only got a hint from this post about how to call these two methods this way: Android BLE onCharacteristicChanged() using notify not triggered
Also, my BroadCastReceiver always shows device bonding as well but never shows device bonded.
The createBond method will internally first connect to the device if not connected using autoConnect set to false. That means the bonding attempt will be aborted after 30 seconds if the device never connects successfully during that time. But you connect using autoConnect set to true, which means no timeout. So if it for some reason takes 31 seconds to connect, the bonding will not happen.
If I were you, I'd first connect the device myself, and when the device has successfully connected and services discovered (and checked that it has the desired services), call createBond, to make sure everything seems right before bonding.
Status code 8 means "Connection Timeout". This means the connection was up and running but dropped unexpectedly on the radio level, which is not a software error, but something that happens naturally as you go out of range but also due to bad hw such as buggy firmware or bad crystal clock frequency.

android BLE - automatic re-connect after spontaneous disconnect

using the android 4.4 BLE APIs on my Nexus7, i'm able to successfully interact with a peripheral BLE device -- connect, disconnect, read, write....
if however an active connection breaks for whatever reason (in this case, the peripheral is reset), i observe the following behavior....
my peripheral (by design) begins advertising after any active connection is terminated (for whatever reason); i can see this via my bluetooth packet sniffer....
i receive the onConnectionStateChanged callback as expected in my android app, at which point i invoke close() on my active BluetoothGatt instance; this is the same procedure i follow during a "normal" disconnect initiated from the client...
shortly after this, the android BLE stack tries to re-connect to the same peripheral; through the packet sniffer i can see the BLE connection request going out over the air...
my app, however, did not initiate this re-connection; indeed, i see no information from any bluetooth log suggesting this even happened!!!!
is there some "mode" in the BLE stack where it attempts to re-establish busted connections automatically???
thanks....
This happens on various Android phones whether the autoConnect flag is set to false or true.
Couldn't yet find a complete solution, it seems as the android BLE stack is spontaneously re-initiating the connection once it is getting the advertising signal again, just ignoring that it was the app that disconnected on purpose...
A partial solution may involve not using the BluetoothGatt.connect() method as explained here:
https://stackoverflow.com/a/23749770/4144487
So, a sample connect method can look like:
void connect(Context context) {
if (mGatt != null) {
mGatt.close();
}
mGatt = mDevice.connectGatt(context, false, callback);
}
To explain the importance of this issue, when it happens the peripheral thinks it is connected and my "real" app can't find it any more. At some phones like Galaxy S3 and Redmi note 3 I found that closing the bluetooth switch from the notification bar is "releasing" the peripheral and allowing me to discover the device. At others like Nexus 5x only a phone reboot will do the trick.
I've observed this happening if you use autoConnect=true when calling BluetoothGatt#connectGatt(). Generally I've found that it is best to use autoConnect=false, but with some devices you simply cannot connect unless you use true, so I usually do both. I try false first and if that fails then use true and then the behavior you're describing is something you simply have to work around.

Android Bluetooth LE: Not discovering services after connection

I'm trying to use Android's Bluetooth Low Energy to communicate with a BLE device. The first time I connect, everything works fine (connecting to GATT server works, all services and characteristics are discovered, etc.) But, if I disconnect and try to re-connect, it will connect to the GATT server, but will not be able to discover the services. I have to kill the app and restart it, and sometimes even that doesn't work.
This is the code I'm using to disconnect from the device:
public void close(View view) {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
Is there anything else that I need to do when disconnecting? There seems to be some resource that is still connected that prevents discovery of services when I try and reconnect.
I seem to have found the solution: you need to call both BluetoothGatt.disconnect() AND BluetoothGatt.close().

Bluetooth is not disabled

I am trying to disable the Bluetooth from my code but it remains enabled and no errors are thrown.
Here is my code.
if (m_BluetoothAdapter.isEnabled()){
m_BluetoothAdapter.disable();
}
if (m_BluetoothAdapter.isEnabled() == false){
Toast.makeText(getApplicationContext(), "BLUETOOTH is being disabled", Toast.LENGTH_SHORT).show();
}
This is the only code in my app for testing.
I also put permission for Bluetooth and Bluetooth_admin.
Neither Eclipse nor mobile gives any error but BT remains enable.
Pl point me what I am doing wrong.
Regards
Update :
Well, I discovered that if I run this app 1st time, BT remains enable.
But if I run app again (2nd time), BT is disabled.
I am not sure why BT is disabled only on the 2nd run and not first time.
Any ideas?
You should know that disable() method makes an asynchronous call so for this reason your code seems not working.
In other words it takes some time when bluetooth will be disabled. In this case you should use BroadcastReceiver with BluetoothAdapter.ACTION_STATE_CHANGED intent-filter and listen for state changes and then make proper actions.
Available states STATE_ON STATE_TURNING_OFF and STATE_OFF
Also look what says docs:
true to indicate adapter shutdown has begun, or false on immediate
error
Use this library , its easy to use and more friendly
also try with below code
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}

Categories

Resources