Android Bluetooth connection does not close after application crashes

I use the SPP profile to connect to my device:

Set<BluetoothDevice> devices = ba.getBondedDevices(); for(BluetoothDevice bd : devices) { String name = bd.getName(); if(name.equals("CELLMETER")) { try { BluetoothSocket bs = bd.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); bs.connect(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } 

Everything looks fine, I created a function where I close the input output buffers and close the socket. But when the application fails or I terminate the application when breakpoints arrive, the socket does not close, even after I killed the process manually, and it is not available for a new connection from a new instance of the application.

What am I doing wrong? For each failure / debug operation, I have to restart the phone :(

This only appeared for Android 2.3.5 (Samsung 5830i) and Android 4.0.4 (Freelander P10). On my Android 4.2.1 (Galaxy Nexus), everything is fine after the emergency connection application closes automatically. (it seems because there is a new Bluetooth stack)

+3
source share
2 answers

I see two options: 1- Add an UncaughtExceptionHandler to your application, best in a class derived from the application:

  mUEHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { // Close any opened sockets here defaultUEH.uncaughtException(t, e); } }; Thread.setDefaultUncaughtExceptionHandler(mUEHandler); 

But this only applies to application crashes. If the user killed the application, he will not be hit at all.

2- Save the socket ID, which will allow you to close it when the application restarts.

This is not ideal, but it can get around your problem.

0
source

I solved this problem by allowing my bluetooth networks to be managed by a service running in its own process. I open, close, read and write sockets, sending messages to and from the Service. If the application crashes, the Service shuts down automatically, closing the sockets. (It does not close if it works in the same process as the application.)

+3
source

Source: https://habr.com/ru/post/1496152/


All Articles