简体   繁体   中英

how to check broadcast unregister or not in android?

In my activity I try to unregister the 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

1) One if I get the result in my onActvityResult

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.

My 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)

Here is my 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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