java.lang.IllegalArgumentException: Receiver not registered

(Of course, if you want) You may register or unregister them in onStop() and onResume() just wrap it with try-catch:

@Override
public void onResume(){
    super.onResume()
    try{ 
        getActivity().registerReceiver(receiver,filter); 
    }catch (Exception e){
        // already registered
    }
}

Or

@Override
public void onStop(){
    try{ 
        getActivity().unregisterReceiver(receiver);  
    }catch (Exception e){
        // already unregistered
    }
    super.onStop()
}

Keep in mind that you must register and unregister on the same context. For example, don't register w/ the application context and unregister w/ the activity context.

Don't do this

getApplicationContext().registerReceiver(myReceiver, myIntentFilter);
unregisterReceiver(myReceiver);

Do this instead (inside an activity)

registerReceiver(myReceiver, myIntentFilter);
unregisterReceiver(myReceiver);

I normally register inside onPostResume() or onResume() and unregister in onPause().

Examples:

protected void onPostResume() {
    super.onPostResume();

    registerReceiver(myReceiver, myIntentFilter);
}

protected void onPause() {
    unregisterReceiver(myReceiver);

    //called after unregistering
    super.onPause();
}

If you register in onCreate(), you have to unregister in onDestroy(). If you want to unregister in onStop() you have to register in onStart().

Have a look at the activity lifecycle here http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

The reason for this is that onStop() is called when the Activity goes into the background, but is not necessarily destroyed. When the Activity comes back to the foreground onStart() is called, but not onCreate() so the BroadcastReceiver isn't re-registered. Then when the Activity goes back into the background, onStop() tries to unregister again, but the receiver has not been registered.

You also need to use the LocalBroadcastManager to unregister your receiver if you used it to register it like so:

LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver);

LocalBroadcastManager is a class from the support library:

Helper to register for and send broadcasts of Intents to local objects within your process.

This is different from the same methods on Context which allow system-wide broadcasts.

Also see a similar question/answer here.

Tags:

Android