1. 程式人生 > >Android 獲取手機充電狀態

Android 獲取手機充電狀態

通過註冊廣播

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 判斷是否充電狀態。