Name is Nilay Name is Nilay - 24 days ago 8
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" />
</intent-filter>
</receiver>


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();
filter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(mybroadcast, filter);

Answer

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);