We have an app that scans for Bluetooth devices. The code responsible for scanning should only run when bluetooth is enabled. Also we want to disable/enable this feature at any point in time.
We choose to implement a BroadcastReceiver that registers for the BluetoothAdapter.ACTION_STATE_CHANGED broadcast.
Here some of the problems we encountered:
Programmatically enable the BroadcastReceiver:
public void registerForBroadcasts(Context context) {
IntentFilter bluetooth = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
context.registerReceiver(this, bluetooth);
}
- When the app is killed, the BroadcastReceiver is also not active anymore. So if the user multi-tasks-swipes the app to death, it is not being woken up again.
- We have full control, when to start the BroadcastReceiver.
Declare the BroadcastReceiver in the Manifest
<receiver android:name="com.mypackage.BroadcastReceiver">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>
</receiver>
- The BroadcastReceiver is active right after the app start.
- The BroadcastReceiver cannot be disabled.
Declare the BroadcastReceiver in the Manifest as disabled + enable it programmatically
<receiver android:name="com.mypackage.BroadcastReceiver"
android:enabled="false" >
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
</intent-filter>
</receiver>
Then enable the component if you need it.
public void registerForBroadcasts(Context context) {
ComponentName component = new ComponentName(context, BroadcastReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(
component,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
My tests have shown, the state is persisted with the system, so the BroadcastReceiver will stay enabled. It combines the advantages of both methods.
- BroadcastReceiver can be disabled
- BroadcastReceiver can be on or off by default
- BroadcastReceiver keeps activation even if app is disabled and phone rebooted.
Am I missing something, does this method seem legit?