supergiox supergiox - 9 months ago 90
Android Question

How to unregister BroadcastReceiver

My app uses a BroadcastReceiver to get sms in this way:

public class SmsBR extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];

for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
if (messages.length > 0)


<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Activity" android:label="@string/app_name">
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

<receiver android:name=".SmsBR">
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>

In this way SmsBR is always ON. I want to register it when a service starts (
) and unregister it when the service is destroyed (
). How can I do this?

Answer Source


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() {

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

  public void onPause() {