Get Battery Level with BroadcastReceiver in Android Service

Yuri Monteiro picture Yuri Monteiro · Jan 18, 2013 · Viewed 19.6k times · Source

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?

Answer

Husam A. Al-ahmadi picture Husam A. Al-ahmadi · Jan 18, 2013

Did you add the following permission to your mainfiest file:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

and change your onReceived Method to:

private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive( Context context, Intent intent )
            {
                int level = intent.getIntExtra( "level", 0 );
                bat= String.valueOf(level) + "%" ;
            }
    };

and to Get the battrey level use this line of code:

registerReceiver( batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED) );