第一步:自定义广播
class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int level = intent.getIntExtra("level", 0); setBattery(level); } }
第一步:注册广播
receiver = new MyReceiver(); IntentFilter intentfilter = new IntentFilter(); //注册动态变化广播 intentfilter.addAction(Intent.ACTION_BATTERY_CHANGED); registerReceiver(receiver, intentfilter);
第三步:设置广播后相应的电量图片
private void setBattery(int level) { if (level <= 0) { ivBattery.setImageResource(R.drawable.ic_battery_0); } else if (level <= 10) { ivBattery.setImageResource(R.drawable.ic_battery_10); } else if (level <= 20) { ivBattery.setImageResource(R.drawable.ic_battery_20); } else if (level <= 40) { ivBattery.setImageResource(R.drawable.ic_battery_40); } else if (level <= 60) { ivBattery.setImageResource(R.drawable.ic_battery_60); } else if (level <= 80) { ivBattery.setImageResource(R.drawable.ic_battery_80); } else if (level <= 100) { ivBattery.setImageResource(R.drawable.ic_battery_100); } else { ivBattery.setImageResource(R.drawable.ic_battery_100); } }