本文介绍了BroadcastReceiver的为内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

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

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

 公共类MyActivity延伸活动{

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

    ...

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

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

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?

解决方案

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

这篇关于BroadcastReceiver的为内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 20:03