Name is Nilay Name is Nilay - 1 year ago 66
Android Question

How to unregister BroadcastReceiver from Activity

It's probably a very simple question but I seem to be hung up on these from a day. So here is the question:

How to unregister a BroadcastReceiver in Activity which was registered from AndroidManifest file?
Here is the code::

<receiver android:name=".PhoneCallReceiver">
<intent-filter >
<action android:name="android.intent.action.PHONE_STATE" />

I am familiar with the function

public void unregisterReceiver (BroadcastReceiver receiver)

but it throws an exception if not registered from that Activity with

IntentFilter filter = new IntentFilter();
registerReceiver(mybroadcast, filter);

Answer Source

To disable a receiver that was defined in the manifest, use the following:

PackageManager pm = context.getPackageManager();
ComponentName component = new ComponentName(context, PhoneCallReceiver.class)
pm.setComponentEnabledSetting(component , PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP);