How to unregister BroadcastReceiver
Edit:
For an Activity:
In order to register your broadcast receiver from within your app, first, remove the <receiver>
tag from your AndroidManifest.xml file. Then, call registerReceiver(BroadcastReceiver receiver, IntentFilter filter)
in your onResume()
. Use unregisterReceiver(BroadcastReceiver receiver)
in your onPause()
to unregister the Broadcast receiver.
For a Service:
Remove the receiver tag from the manifest file. You can then register your Broadcast receiver with the same method in the onCreate()
and unregister in the onDestroy()
.
EDIT: Sample Code:
public class MyActivity extends Activity {
private final BroadcastReceiver mybroadcast = new SmsBR();
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mybroadcast, filter);
}
public void onPause() {
super.onPause();
unregisterReceiver(mybroadcast);
}
}
onDestroy()
is not guaranteed to be called. When you start Activity from Activty, onPause()
and onStop()
method called instead of onDestroy()
.
onDestroy()
calls when you hit back button or call finish()
method.
Hence, broadcast receiver should be registered in onStart()
or onResume()
, and unregister receiver in onPause()
or onStop()
.
If you unregister receiver in onDestroy()
method, it might cause a memory leak in App.