Reputation: 21
It is my understanding that "well-behaved" Android apps will unregister their broadcast receivers in onPause(). But this is complicated when you're enabling Bluetooth discoverability.
Let's say my well-behaved Activity unregisters its BLUETOOTH_SCAN_MODE_CHANGED receiver in its onPause(). Then, the user taps a button in-app to enable discoverability and this code is run:
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(discoverableIntent);
In all cases I've encountered so far, the broadcast intent is fired before my Activity's onResume() method is called, which means it is fired before my Activity re-registers its receiver, and the Activity does not receive the broadcast intent that Bluetooth was made discoverable.
My workaround is to just leave the broadcast intent in place, i.e., to not unregister it in onPause().
My questions are: is there a better workaround? and is it actually bad to leave broadcast receivers registered between onPause() and onResume()? Thanks!
Upvotes: 0
Views: 170
Reputation: 17
You can get the current Bluetooth discoverable state in onResume() like this:
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
boolean discoverable = adapter.getScanMode() == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE;
That way you can continue to unregister your broadcast receiver in onPause() and re-register it in onResume().
Upvotes: 1
Reputation: 242
You could delegate Bluetooth interaction to a Service. The BroadcastReceiver could be registered/unregistered by the Service, which lives across the Activity's lifecycle. Living in the same process of the Service, the Activity can connect to it as soon as it is resumed and get anything received by the BroadcastReceiver.
Upvotes: 0