Register BroadcastReceiver in non-activity class

android, android-context, broadcastreceiver, java, xml

Solution

There are two problems here:

ρяσѕρєя K has pointed out the first one:

Initialize your context by adding a parameter to the method CheckBatteryLevel() or to the constructor of MyClass

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

Second, you have to call registerReceiver(..) AFTER you have initialized the BroadcastReceiver. Or it will be null and not registered.

All in all this should do it:

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

Problem

I have to use a BroadcastReceiver in a class that I will have to call in an Activity. Obviously, I have to necessarily register the BroadcastReceiver and then I wrote this code: ``` 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 } } }; } } ``` When I run the code the application crashes giving "`Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) }` and the crash line is ``` context.registerReceiver(batteryInfoReceiverLevel, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); ``` How can i fix?

Original source