SAM
SAM

Reputation: 11

Getting battery status from a service in Android

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.

Upvotes: 1

Views: 10202

Answers (4)

Marco
Marco

Reputation: 11

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

Upvotes: 1

tobias
tobias

Reputation: 2362

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

Upvotes: 6

Remi Peuvergne
Remi Peuvergne

Reputation: 279

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

Upvotes: 5

user1049280
user1049280

Reputation: 5246

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

Upvotes: 0

Related Questions