Wednesday, August 17, 2011

Leaked IntentReceiver?

Ok, so total noob here. Learned the hard way. It's tempting to register an anonymous inner class instance as a broadcast receiver and forget about it, like this:

 registerReceiver(new BroadcastReceiver() {
   @Override
   public void onReceive(Context arg0, Intent arg1) {
    // code here...
   }
  }, new IntentFilter(...));


If you do that, when you switch orientation (ctrl-F11 in the emulator), you'll see an exception like this:

ERROR/ActivityThread(1585): Activity com.foo.SomeActivity has leaked IntentReceiver com.foo.SomeActivity$2@405266b8 that was originally registered here. Are you missing a call to unregisterReceiver()?


So using an anonymous inner class is a bad idea.  You have to hang onto the reference to the BroadcastReceiver instance in a member variable of the Activity and release it in onDestroy:

 @Override
 protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(syncCompleteReceiver);
 }

No comments:

Post a Comment