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

你可能感兴趣的:(省电续航)