Search code examples
androidandroid-activitybroadcastreceiverandroid-broadcastreceiverondestroy

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

Solution

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