Android 判斷電池是否為充電狀態的方法
阿新 • • 發佈:2018-11-21
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