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?