如何在Android中检查广播取消注册?

时间:2017-04-08 10:59:44

标签: android android-activity broadcastreceiver android-broadcastreceiver ondestroy

在我的活动中,我尝试取消注册Broadcast Receiver。我只是把这一行放在那里取消注册。

unregisterReceiver(myBroadcastReceiver);

但问题是我的Broadcast在两个条件下取消注册

1)如果我在onActvityResult

中得到结果,则为1

2)onDestroy

但问题是,当Broadcast Receiver取消注册来自onActvityResult并且当用户尝试关闭Activity我的onDestroy时,我的应用程序将被崩溃。

  

我的Logcat:

     

引起:java.lang.IllegalArgumentException:Receiver not   注册:   com.coincide.ridetog.post_ride.PostRideActvity$MyBroadcastReceiver@831c755                                                                             在android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:782)                                                                             在android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1205)                                                                             在   android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:586)                                                                             在   com.coincide.ridetog.post_ride.PostRideActvity.onDestroy(PostRideActvity.java:300)

这是我的onDestroy()

@Override
protected void onDestroy() {
    super.onDestroy();
    if (myBroadcastReceiver!=null) {
        unregisterReceiver(myBroadcastReceiver);
    }
}

1 个答案:

答案 0 :(得分:2)

在您的活动中添加以下方法,并在onResume和onActivityResult回调中调用它。调用方法后,它会将myBroadcastReceiver实例设置为null,因此在创建新的myBroadcastReceiver实例之前,它将避免多次执行。

private void unregisterMyBroadcastReceiver() {
    if (null != myBroadcastReceiver) {
        unregisterReceiver(myBroadcastReceiver);
        myBroadcastReceiver = null;
    }
}