我需要知道(通过我的应用程序)Android设备是否正在充电。有任何想法吗?谢谢

最佳答案

我发现的一件事是,如果手机的电池电量为100%,则不会收到充电通知。有些人指的是充电,而另一些人指的是具有外部电源(无论其是否为100%)时。我将它们归为一,如果满足任何条件,则返回true。

public static boolean isPhonePluggedIn(Context context){
    boolean charging = false;

    final Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean batteryCharge = status==BatteryManager.BATTERY_STATUS_CHARGING;

    int chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

    if (batteryCharge) charging=true;
    if (usbCharge) charging=true;
    if (acCharge) charging=true;

    return charging;
}

07-27 17:48