Getting battery status from a service in Android

拟墨画扇 提交于 2019-12-06 17:32:25

Use ACTION_BATTERY_CHANGED. It is called every time the battery value changes. See the code below to see how it is done:

public void onCreate()
{

this.registerReceiver(this.mBatInfoReceiver, 
        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {

    int level = intent.getIntExtra("level", 0);
    Log.e("test", String.valueOf(level) + "%");

     }
};


public void onDestroy(){

    // unregister receiver
    this.unregisterReceiver(this.mBatInfoReceiver);
}

What's the difference ? You should be able to register a receiver for battery events in the service, the same way as you do with an activity. For example:

private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
        int rawLevel = intent.getIntExtra("level", -1);
        int scale = intent.getIntExtra("scale", -1);
        int status = intent.getIntExtra("status", -1);
        // Do something
    }
};

public void onCreate() {
    registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

public void onDestroy() {
     unregisterReceiver(this.mBatInfoReceiver);
}

I think you must use ACTION_BATTERY_CHANGED. Note that it's a sticky intent, so you don't need to monitor it directly in a broadcast receiver. You can get a reference directly from an Activity.

From android documentation:

Because it's a sticky intent, you don't need to register a BroadcastReceiver—by simply calling registerReceiver passing in null as the receiver as shown in the next snippet, the current battery status intent is returned.

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!