BroadcastReceiver的为内部类部类、BroadcastReceiver

2023-09-12 22:05:32 作者:他的爱っ我的情

我知道,如果定义为活动的内部类的BroadcastReceiver不能使用。但我不知道为什么?难道是因为系统必须实例化一个大型活动的对象只是实例化一个recevier实例?

解决方案   

...因为系统必须实例化一个大的活动对象只是还instanitated一个recevier实例?

是啊,就像任何其他非静态内部类。它有(通过实例或通过其他方式,例如),才可以创建(非静态)内部类的一个实例来从某处外部类的一个实例。

这是从意图在于将被系统自动实例化的清单文件调用的全球广播接收器有没有这样的外部实例用于创建广播​​接收机非静态内部类的一个实例。这是不以什么样的外部类,活动与否。

不过,如果您使用的是接收器与一个活动的工作的一部分,您可以手动实例化一个广播接收器在自己的活动(而活动回调中的一个,你有外部类一起工作的一个实例: ),然后注册/注销其作为合适的:

 公共类MyActivity延伸活动{

    私人BroadcastReceiver的myBroadcastReceiver =
        新的BroadcastReceiver(){
            @覆盖
            公共无效的onReceive(...){
                ...
            }
       });

    ...

    公共无效onResume(){
        super.onResume();
        ....
        registerReceiver(myBroadcastReceiver,IntentFilter的);
    }

    公共无效的onPause(){
        super.onPause();
        ...
        unregisterReceiver(myBroadcastReceiver);
    }
    ...
}
 

第64课 BroadcastReceiver广播组件之静态注册

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