1. 程式人生 > >Android 判斷電池是否為充電狀態的方法

Android 判斷電池是否為充電狀態的方法

1. 工具類方法

package com.android.settings.fuelgauge;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;

public class InonePowerSaveUtil {

    public static final boolean IS_CHARGE_DISABLE = true;

    public static boolean isChargingDisable(Context context) {
        return IS_CHARGE_DISABLE && isCharging(context);
    }

    public static boolean isCharging(Context context) {
        Intent batteryBroadcast = context.registerReceiver(null,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        // 0 means we are discharging, anything else means charging
        boolean isCharging = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) != 0;
        Log.d(InonePowerSaveUtil.class.getSimpleName(),"isCharging = " + isCharging );
        return isCharging;
    }
}

執行日誌

10-31 12:15:50.318  6191  6191 D InonePowerSaveUtil: isCharging = true
10-31 12:18:40.574  6191  6191 D InonePowerSaveUtil: isCharging = false

2. 測試驗證

2.1 模擬不充電命令 adb shell dumpsys battery unplug