Search code examples
androidservicebatterybatterylevel

Get Battery Level with BroadcastReceiver in Android Service


I have a code, that I need get the Battery Level of my Android device, but I have a big problem. I have an Android Service where I go get battery level and send by UDP.

This is my Service code:

public class Servico extends Service {

String bateria = "Nada";

/*
 * Recupera nível de bateria
 */
private BroadcastReceiver BatInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context arg0, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        bateria = String.valueOf(level);
    }
};

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(), "Command=" + bateria + "%", Toast.LENGTH_LONG).show();
    stopSelf();
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(BatInfoReceiver);
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

}

My problem is: I cannot get the level! I put a BreakPoint into onReceive method in BatInfoReceiver, but this code only is executed after the execute onStartCommand, and e NEED use the value of battery level into onStartCommand.

How can I do it?


Solution

  • take a look at this, it will get you the battery level you need so you can start your service. Just use BatteryManager.EXTRA_LEVEL as the key to get the level from the intent

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