In an application I have a main activity and several fragments, the application works by connecting to two bluetooth devices.
What I need is that before closing THE APPLICATION disconnect and turn off the bluetooth of the mobile. I have tried with the onDestoy() and onPause() methods inside the MainActivity but I don't have the expected results because although the blue turns off the application becomes unstable and exceptions are generated and it cannot exit normally.
Can someone guide me with the method on which I should program. Thank you very much.
@Override
public void onDestroy(){
super.onDestroy();
try {
mBluetoothAdapter.disable();
mBluetoothGatt.disconnect();
} catch (Exception ex) {
}
}
I emphasize the problem is not the lines of code, because if they turn off the bluetooth, but it is the event within which I do it that generates unwanted exceptions.
Check out this answer from @BradHein , you should first close the streams and open connections and then the BluetoothAdapter/BluetoothManager :
method
resetConnection()
:Check the life cycle of the
Activity
:Which method you should choose depends on the behavior you are expecting from your application. If you want to disable Bluetooth when another application is brought to the foreground (the user switches tasks, for example), you should use the
onResume()
and methodsonPause()
.If you want to disable BT when your app is completely destroyed, then
onDestroy()
.Regarding the errors that you are receiving, I suggest that you apply the following criteria when calling the methods of the class
super
.When you override a method that creates your application (onCreate, onResume, etc.) you should call the parent class method first (with
super.onResume()
).When you override a method that destroys your app (onDestroy, onPause, etc.), call the parent class's method last (
super.onPause()
)I give you an example:
Please take this as a general rule, as there are always exceptions.