在电话重启时取消广播接收器。

时间:2012-11-09 09:36:15

标签: android networking broadcastreceiver

我有BroadcastReceiver(NetworkListener)。

public class NetworkReceiver extends BroadcastReceiver {
Context context;
public static NetworkReceiver instance = new NetworkReceiver();
public static InnerObservable observable = instance. new InnerObservable();
...

此接收方发送通知:

@Override
public void onReceive(Context ctx, Intent intent) {

    Log.d("tag", "onReceive");

    NotificationManager notif = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(android.R.drawable.ic_dialog_alert,"bla-bla-bla",System.currentTimeMillis());

清单文件:

 <receiver 
        android:name="com.mypckg.network.NetworkReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver> 

工作正常。但手机重启后,它继续工作。怎么避免呢?

2 个答案:

答案 0 :(得分:1)

如果您希望广播接收器在应用程序启动时开始工作,那么您应该从主要活动中以编程方式注册/取消注册它:

private BroadcastReceiver networkReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    networkReceiver = new NetworkReceiver();
    registerReceiver(networkReceiver, ConnectivityManager.CONNECTIVITY_ACTION);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(networkReceiver)
}

答案 1 :(得分:1)

您可以使用PackageManager来禁用清单中注册的BroadcastReceiver,请检查this thread for code.

另一种解决方案是动态注册此接收器,可能在服务中。只要服务处于活动状态,接收器就会处于活动状态并进行注册,因此您可以通过启动/停止服务轻松切换接收器。这可能不适合您的用例,但是您没有提供太多详细信息。