开发者

BroadcastReceiver as inner class

I know the B开发者_开发知识库roadcastReceiver 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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜