Android 获取手机充电状态

移动开发 waitig 627℃ 百度已收录 0评论

通过注册广播

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 判断是否充电状态。


本文由【waitig】发表在等英博客
本文固定链接:Android 获取手机充电状态
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)