Create a class BatteryReceiver extends BroadcastReceiver.
class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_OKAY)) {
// int level = intent.getIntExtra("level", 0);
} else if (intent.getAction().equalsIgnoreCase(
Intent.ACTION_BATTERY_CHANGED)) {
} else if (intent.getAction().equalsIgnoreCase(
Intent.ACTION_BATTERY_LOW)) {
}
}
}
Now In your Activity, where you wanna get the battery deatails paste below code:
private void setBatteryInfo() {
// declair globally >> aBatteryReceiver
// private BatteryReceiver aBatteryReceiver;
aBatteryReceiver = new BatteryReceiver();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
final Intent batteryIntent = registerReceiver(aBatteryReceiver,
mIntentFilter);
runOnUiThread(new Runnable() {
@Override
public void run() {
final BatteryInfo aBatteryInfo = getBatteryLevel(batteryIntent);
String test = "";
test += "Health: " + aBatteryInfo.getHealth() + "\n";
test += "Level: " + aBatteryInfo.getLevel() + "%\n";
test += "Plugged: " + aBatteryInfo.getPlugged() + "\n";
test += "Present: " + aBatteryInfo.isPresent() + "\n";
test += "Status: " + aBatteryInfo.getStatus() + "\n";
test += "Technology: " + aBatteryInfo.getTechnology() + "\n";
test += "Temperature: " + aBatteryInfo.getTemperature()
+ " celsius\n";
test += "Voltage: " + aBatteryInfo.getVoltage() + " mV\n";
textViewBatteryDescription.setText(test);
}
});
}
@Override
protected void onDestroy() {
// don't forget to destroy the receiver
try {
super.onDestroy();
this.unregisterReceiver(aBatteryReceiver);
if (adView != null) {
adView.destroy();
}
} catch (Exception e) {
Toast.makeText(context, SOME_INFORMATION_NOT_AVAILABLE,
Toast.LENGTH_SHORT).show();
}
}