Getting battery status from a service in Android

跟風遠走 提交于 2020-01-03 03:28:29

问题


I am developing an app for which I need to monitor the remaining battery percentage from a service. Can anybody tell me how to do it? I found some sample codes that are getting the battery status from an activity, not from service.

Thanks.


回答1:


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



回答2:


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



回答3:


Here's what you need via BroadcastReceiver: http://developer.android.com/training/monitoring-device-state/battery-monitoring.html




回答4:


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



来源:https://stackoverflow.com/questions/12283454/getting-battery-status-from-a-service-in-android

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