Dynamic broadcast receiver registration

1. Dynamically registered receiver

Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context.registerReceiver() and Context.unregisterReceiver() methods.

Note: Do not forget to unregister a dynamically registered receiver by using Context.unregisterReceiver() method. If you forget this, the Android system reports a leaked broadcast receiver error. For instance, if you registered a receive in onResume() methods of your activity, you should unregister it in the onPause() method. 

2. Using the package manager to disable static receivers

You can use the PackageManager class to enable or disable receivers registered in your AndroidManifest.xml file.

ComponentName receiver = new ComponentName(context, myReceiver.class);
PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);

3. Sticky (broadcast) intents

An intent to trigger a receiver ( broadcast intent ) is not available anymore after it was sent and processed by the system. If you use the sendStickyBroadcast(Intent) method, the corresponding intent is sticky, meaning the intent you are sending stays around after the broadcast is complete.
The Android system uses sticky broadcast for certain system information. For example, the battery status is send as sticky intent and can get received at any time. The following example demonstrates that.

// Register for the battery changed event
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

/ Intent is sticky so using null as receiver works fine
// return value contains the status
Intent batteryStatus = this.registerReceiver(null, filter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
        || status == BatteryManager.BATTERY_STATUS_FULL;

boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
 
You can retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)' . This also works for a null `BroadcastReceiver .
In all other ways, this behaves just as sendBroadcast(Intent) .
Sticky broadcast intents typically require special permissions.
 

1 comment:

  1. Dynamic broadcast receiver registration in Android allows apps to register and unregister broadcast receivers during runtime. Camera Apps Security This flexibility enables apps to respond to specific events as needed.

    ReplyDelete