android - 如何注销广播接收器

标签 android broadcastreceiver

我的应用程序使用广播接收器以这种方式获取短信:

SmsBR.java

public class SmsBR extends BroadcastReceiver {

    @Override
    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)
                //doSomething();
            }
        }
    }
}

Manifest.xml

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

    <receiver android:name=".SmsBR">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
        </intent-filter>
    </receiver>
</application>    

这样,SmsBR 始终处于开启状态。我想在服务启动时注册它(onCreate()),并在服务销毁时取消注册(onDestroy())。我该怎么做?

最佳答案

编辑:

对于 Activity :

为了在您的应用程序中注册您的广播接收器,首先,删除 <receiver> AndroidManifest.xml 文件中的标记。然后,调用registerReceiver(BroadcastReceiver receiver, IntentFilter filter)在您的onResume() .使用unregisterReceiver(BroadcastReceiver receiver)在您的onPause()取消注册广播接收器。

对于服务:

从 list 文件中删除接收者标签。然后,您可以在 onCreate() 中使用相同的方法注册您的广播接收器。并在 onDestroy() 中注销.

编辑:示例代码:

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

关于android - 如何注销广播接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7439041/

相关文章:

android - 是否有基于 Android 的 Google Glass 模拟器?

java - 如何让安卓应用程序在一天中的特定时间做某事

Android 应用程序架构 - 在哪里放置 REST API 调用代码?

19+ api 中用于 SMS 的 Android 静态广播接收器(当应用程序关闭时)

java - 在 Activity/fragment 中确认警报对话框后,如何在单击时更新我的​​ RecyclerView 按钮状态?

android - LocalBroadcastReceiver 在线程内部不起作用

java - 测试 getJSONArray 是否为 null

android - 水平滚动 GridView

android - 经过验证的 cordova 应用程序可以验证应用程序内的 Web View 吗?

java - 警报管理器未触发服务