简体   繁体   English

如何检查广​​播注销或不在android中?

[英]how to check broadcast unregister or not in android?

In my activity I try to unregister the Broadcast Receiver . 在我的活动中,我尝试注销Broadcast Receiver注册。 I'm simply putting this line for unregister that. 我只是将这一行用于注销。

unregisterReceiver(myBroadcastReceiver);

But the problem is that my Broadcast is unregister on two condition 但是问题是我的Broadcast在两种情况下都未注册

1) One if I get the result in my onActvityResult 1)如果我在onActvityResult得到结果

2) onDestroy 2)在onDestroy

But problem is that when my Broadcast Receiver unregister from the onActvityResult and when user try to close the Activity my onDestroy is called and my application is crashed. 但是问题是,当我的Broadcast ReceiveronActvityResult注销时,并且当用户尝试关闭Activity我的onDestroy被调用,我的应用程序崩溃了。

My Logcat: 我的Logcat:

Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.coincide.ridetog.post_ride.PostRideActvity$MyBroadcastReceiver@831c755 at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:782) at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1205) at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:586) at com.coincide.ridetog.post_ride.PostRideActvity.onDestroy(PostRideActvity.java:300) 造成原因:java.lang.IllegalArgumentException:接收者未注册:com.coincide.ridetog.post_ride.PostRideActvity$MyBroadcastReceiver@831c755在android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:782)在android.app.ContextImpl.unregisterReceive ContextImpl.java:1205)位于android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:586)位于com.coincide.ridetog.post_ride.PostRideActvity.onDestroy(PostRideActvity.java:300)

Here is my onDestroy() 这是我的onDestroy()

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

Add following method in your activity and call it in your onResume and in your onActivityResult callbacks. 在您的活动中添加以下方法,并在您的onResume和onActivityResult回调中调用它。 Once method is called it will set your myBroadcastReceiver instance to null, so it will avoid to execute multiple times until you create a new myBroadcastReceiver instance. 调用方法后,它将myBroadcastReceiver实例设置为null,因此它将避免执行多次,直到创建新的myBroadcastReceiver实例为止。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM