在非活动类中注册BroadcastReceiver

时间:2013-12-08 13:06:46

标签: java android xml broadcastreceiver android-context

我必须在一个我必须在Activity中调用的类中使用 BroadcastReceiver 。显然,我必须注册 BroadcastReceiver ,然后我写了这段代码:

    public class MyClassName {

        Context context;
        BroadcastReceiver batteryInfoReceiverLevel;

        public void CheckBatteryLevel() {

        Log.d("App", "I'm in the CheckBatteryLevel");

        context.registerReceiver(batteryInfoReceiverLevel, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

        batteryInfoReceiverLevel = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

            Log.d("Apps", "I'm in the onReceive");

            int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);

            if(level <=100) {
//Do something

            }

            else if(level >=100) {
//Do something
            }

            }

            };

        }

    }

当我运行代码时,应用程序崩溃了#34; Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) }并且崩溃线是

context.registerReceiver(batteryInfoReceiverLevel, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

我该如何解决?

2 个答案:

答案 0 :(得分:1)

  

应用程序崩溃,显示“接收广播意图错误

由于context为空,因此您需要在调用context之前初始化registerReceiver。初始化时使用类构造函数或从调用Activity传递给CheckBatteryLevel方法。 :

public void CheckBatteryLevel(Context aContext) {

context =aContext;
//....your code here...
}

答案 1 :(得分:1)

这里有两个问题:

ρяσѕρєяK指出了第一个:

通过向方法CheckBatteryLevel()或构造函数添加参数来初始化上下文 of MyClass

public class MyClass(Context ctx) {
    context = ctx;
}

其次,您必须在初始化BroadcastReceiver之后调用registerReceiver(..)。或者它将为null并且未注册。

总而言之,这应该做到:

public class MyClassName {

    BroadcastReceiver batteryInfoReceiverLevel;

    public void CheckBatteryLevel(Context ctx) {

        Log.d("App", "I'm in the CheckBatteryLevel");

        batteryInfoReceiverLevel = new BroadcastReceiver() { // init your Receiver

            @Override
            public void onReceive(Context context, Intent intent) {

                Log.d("Apps", "I'm in the onReceive");
                int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
                if(level <=100) {
                    //Do something
                } else if(level >=100) {
                    //Do something
                }
            }
        };
        // register your Receiver after initialization 
        ctx.registerReceiver(batteryInfoReceiverLevel,
                  new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 
    }
}