Android 获取手机充电状态

  • Post author:
  • Post category:其他


通过注册广播

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(TAG, "action is " + action);
        switch (action) {
            case Intent.ACTION_POWER_CONNECTED:
            case "test.charge":
                mCharge = true;
                break;

            case Intent.ACTION_POWER_DISCONNECTED:
            case "test.uncharge":
                mCharge = false;
                break;

            case Intent.ACTION_BATTERY_CHANGED:
                mBatteryPercent = intent.getIntExtra("level", 100);
                int state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                Log.d(TAG, " battery state is " + state);
                mCharge = (state == BatteryManager.BATTERY_STATUS_FULL) || (state == BatteryManager.BATTERY_STATUS_CHARGING);

                mLowerPower = mBatteryPercent <= mLowBatteryWarningPercent ? true : false;
                /* when power charging ,the lowerpower flag false*/
                if (mCharge) {
                    mLowerPower = false;
                }
                break;

通过注册

Intent.ACTION_POWER_CONNECTED

Intent.ACTION_POWER_DISCONNECTED

来获取手机插拔数据线状态。

通过注册

Intent.ACTION_BATTERY_CHANGED

来监听电量变化

                case Intent.ACTION_BATTERY_CHANGED:
                    mBatteryPercent = intent.getIntExtra("level", 100);
                    int state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                    Log.d(TAG, " battery state is " + state);
                    mCharge = (state == BatteryManager.BATTERY_STATUS_FULL) || (state == BatteryManager.BATTERY_STATUS_CHARGING);

通过

int state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

来得到state 状态

state == BatteryManager.BATTERY_STATUS_CHARGING 判断是否充电状态。



版权声明:本文为wangjicong_215原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。