简体   繁体   中英

calling BroadcastReceiver from Activity

I am newbie in android programming; sorry if my question is easy :) I'm trying to write code that monitors the battery level on the phone and if it is, lower some level for example (%15), create a message that asks user to plug the charger. I know that I need to use BroadcastReceiver class and I want to use it in my MainActivity class. Here is the code I have:

public class MainActivity extends Activity{
BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(final Context context, Intent intent) {
        String intentAction = intent.getAction();
        Log.d("receiver", intentAction);
        int level = intent.getIntExtra("level", 0);
        if (level < 15){
            Log.d("receiver", "battery level low");
        }

        if (Intent.ACTION_BATTERY_OKAY.equalsIgnoreCase(intentAction)) {
            Log.d("receiver", "battery level okay");
        }
    }
};
......

but it seems that the onReceive method is never called since I never see the Log.d("receiver", intentAction) message on Android Studio debug window. I also have registered br in onResume and unregistered it in onPause :

public void onResume() {
    super.onResume();
    filter.addAction("receiver");
    registerReceiver(br, filter);
}

public void onPause() {
    super.onPause();
    unregisterReceiver(br);
}

But still I am not getting any message. Can anybody please help me? Should I also add something to AndroidManifest.xml ?

Your code in onResume() is wrong. You will have to update it as follows.

    filter.addAction(Intent.ACTION_BATTERY_LOW);
    filter.addAction(Intent.ACTION_BATTERY_OKAY);
    registerReceiver(br, filter);

to include the ACTION_BATTERY_LOW and ACTION_BATTERY_OKAY filters as mentioned in the docs .

If you dont want to use BroadcastReceiver simply dont use it. Battery intent is sticky intent so you can check it without need of BroadcastReceiver and i also dont think its good idea to put receiver in activity. You can check battery stuff in your activity like this and you dont need to edit your manifest

IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, filter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
if(batteryPct < 15){
    //do your stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM