Get battery level and state in Android
Here is a code sample that explains how to get battery information.
To sum it up, a broadcast receiver for the ACTION_BATTERY_CHANGED
intent is set up dynamically, because it can not be received through components declared in manifests, only by explicitly registering for it with Context.registerReceiver()
.
public class Main extends Activity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level * 100 / (float)scale;
batteryTxt.setText(String.valueOf(batteryPct) + "%");
}
};
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
Since SDK 21
LOLLIPOP
it is possible to use the following to get current battery level as a percentage:
BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
Read BatteryManager | Android Developers - BATTERY_PROPERTY_CAPACITY
Based on official android docs, you can use this method in a Helper or Util class to get current battery percentage:
Java version:
public static int getBatteryPercentage(Context context) {
if (Build.VERSION.SDK_INT >= 21) {
BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, iFilter);
int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
double batteryPct = level / (double) scale;
return (int) (batteryPct * 100);
}
}
Kotlin version:
fun getBatteryPercentage(context: Context): Int {
return if (Build.VERSION.SDK_INT >= 21) {
val bm = context.getSystemService(BATTERY_SERVICE) as BatteryManager
bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus: Intent = context.registerReceiver(null, iFilter)
val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
val batteryPct = level / scale.toDouble()
(batteryPct * 100).toInt()
}
}