Android 获取设备电池电量

注册广播接收器:

homeFilter = new IntentFilter();
homeFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(homeReceiver, homeFilter);

广播接收ACTION_BATTERY_CHANGED:

private BroadcastReceiver homeReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                int rawLevel = intent.getIntExtra("level", -1);
                int scale = intent.getIntExtra("scale", -1);
                int status = intent.getIntExtra("status", -1);
                int health = intent.getIntExtra("health", -1);
                MyLog.i("[HomeReceiver]rawLevel:" + rawLevel + ",scale:"
                        + scale + ",status:" + status + ",health:" + health);

                switch (status) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    setBatteryImageByLevel(0);
                    break;

                case BatteryManager.BATTERY_STATUS_CHARGING:
                    break;

                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    if (rawLevel >= 0 && rawLevel <= 100) {
                        int level = (int) (rawLevel / 10.0);
                        setBatteryImageByLevel(level);
                    }
                    break;

                case BatteryManager.BATTERY_STATUS_FULL:
                    setBatteryImageByLevel(10);
                    break;

                default:
                    break;
                }

            }
        }
    };

设置电池图标:

    /**
     * 设置电池图标
     * 
     * @param level
     *            0-10
     */
    private void setBatteryImageByLevel(int level) {
        MyLog.i("[setBatteryImageByLevel]:" + level);
        if (level >= 0 && level <= 10) {
            int batteryResId = getResources().getIdentifier(
                    "home_battery_" + level, "drawable", getPackageName());
            imageBattery.setImageResource(batteryResId);
        }
    }

你可能感兴趣的:(Android)