I know the BroadcastReceiver
can't be used if defined as Activity's inner class. But I wonder why? Is it because the system would have to instantiate a large Activity
object to just have instantiated a receiver instance?

- 10,019
- 9
- 74
- 96

- 42,730
- 18
- 77
- 103
1 Answers
... because the system would have to instantiate a large Activity object to just have instanitated a recevier instance?
Yup, just like any other non-static inner class. It has to get an instance of the outer class from somewhere (e.g. by instantiating or by some other mechanism) before it can create an instances of the (non-static) inner class.
Global broadcast receivers that are invoked from intents in the manifest file that would be be instantiated automatically by the system have no such outer instance to use to create an instance of the broadcast receiver non-static inner class. This is independent of what the outer class is, Activity or not.
However, if you are using a receiver as part of working with an activity, you can manually instantiate a broadcast receiver yourself in the activity (while one of the activity callbacks, you have an instance of the outer class to work with: this
) and then register/unregister it as appropriate:
public class MyActivity extends Activity {
private BroadcastReceiver myBroadcastReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(...) {
...
}
});
...
public void onResume() {
super.onResume();
....
registerReceiver(myBroadcastReceiver, intentFilter);
}
public void onPause() {
super.onPause();
...
unregisterReceiver(myBroadcastReceiver);
}
...
}

- 85,407
- 12
- 106
- 123
-
I have tried to use an inner class as you suggest (and also as I saw in some examples online): https://gist.github.com/daviddoria/80c9c5dc98913b54bf00 but onReceive is not called when I rotate my device. Any suggestions? – David Doria Oct 08 '13 at 18:05
-
3bert is this leads to any memory leaks by holding the outer class object?? – kalyan pvs Jun 19 '14 at 07:14