Create an inner class with our BroadcastReceiver realization:
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
txvlebtry.setText(String.valueOf(level)+"%" );
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
if (health == BatteryManager.BATTERY_HEALTH_COLD) {
btry_health_val.setText(R.string.cold);
}
if (health == BatteryManager.BATTERY_HEALTH_DEAD) {
btry_health_val.setText(R.string.dead);
}
if (health == BatteryManager.BATTERY_HEALTH_GOOD) {
btry_health_val.setText(R.string.good);
}
if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT) {
btry_health_val.setText(R.string.overheat);
}
if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE) {
btry_health_val.setText(R.string.overVoltage);
}
if (health == BatteryManager.BATTERY_HEALTH_UNKNOWN) {
btry_health_val.setText(R.string.unknown);
}
int temprature = (intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10;
tempraturebtry_val.setText(temprature + R.string.degreecel);
int chargeplug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
if (chargeplug == BatteryManager.BATTERY_PLUGGED_AC) {
chargeplug_val.setText(R.string.acadapter);
}
if (chargeplug == BatteryManager.BATTERY_PLUGGED_USB) {
chargeplug_val.setText(R.string.USB);
}
if (chargeplug == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
chargeplug_val.setText(R.string.Wireless);
}
int status = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
btrystatus_val.setText(R.string.Charging);
}
if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
btrystatus_val.setText(R.string.Discharging);
}
if (status == BatteryManager.BATTERY_STATUS_FULL) {
btrystatus_val.setText(R.string.Full);
}
if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
btrystatus_val.setText(R.string.notchargin);
}
if (status == BatteryManager.BATTERY_STATUS_UNKNOWN) {
btrystatus_val.setText(R.string.unknown);
}
}
};
Then register our BroadcastReceiver in application
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
CLICK HERE to find out more related problems solutions.