private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
BatteryManager.BATTERY_STATUS_UNKNOWN);
Log.e("", "level-->" + level + "\nscale-->" + scale +
"\nstatus-->" + status);
if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
ivBattery.setImageResource(R.drawable.battery_chongdian) ;
} else {
int l = -1;
if (level >= 0 && scale > 0) {
l = level * 100 / scale;
}
if (l >= 85) {
ivBattery.setImageResource(R.drawable.battery_full);
} else if (l >= 70 && l < 85) {
ivBattery.setImageResource(R.drawable.battery_bashi) ;
} else if (l >= 50 && l < 70) {
ivBattery.setImageResource(R.drawable.battery_wushi) ;
} else if (l >= 30 && l < 50) {
ivBattery.setImageResource(R.drawable.battery_sanshi) ;
} else if (l >= 16 && l < 30) {
ivBattery.setImageResource(R.drawable.battery_sanshi) ;
} else if (l >= 0 && l < 16) {
ivBattery.setImageResource(R.drawable.battery_ling) ;
}
}
}
}
};
Android中监听电池变化
最新推荐文章于 2022-11-22 18:38:53 发布