Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

android - BroadcastReceiver as inner class

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...