Android BroadcastReceiver Enabling and disabling a Broadcast Receiver programmatically

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

To enable or disable a BroadcastReceiver, we need to get a reference to the PackageManager and we need a ComponentName object containing the class of the receiver we want to enable/disable:

ComponentName componentName = new ComponentName(context, MyBroadcastReceiver.class);
PackageManager packageManager = context.getPackageManager();

Now we can call the following method to enable the BroadcastReceiver:

packageManager.setComponentEnabledSetting(
    componentName,
    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    PackageManager.DONT_KILL_APP);

Or we can instead use COMPONENT_ENABLED_STATE_DISABLED to disable the receiver:

packageManager.setComponentEnabledSetting(
    componentName,
    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
    PackageManager.DONT_KILL_APP);


Got any Android Question?