Register BroadcastReceiver in an inactive class

I need to use BroadcastReceiver in a class that I will need to call in Activity. Obviously, I have to register BroadcastReceiver , and then 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, " Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) }and the line of failure

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

How can i fix it?

+4
source share
2 answers

There are two problems here:

ρσѕρє K pointed to the first:

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

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

-, registerReceiver (..) , BroadcastReceiver. .

:

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

, " "

context null, context registerReceiver. CheckBatteryLevel Activity.

public void CheckBatteryLevel(Context aContext) {

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

All Articles