Java – how do I know if my phone is charging

I need to know (through my app) whether the Android device is charging Any ideas? thank you

Solution

One thing I found is that if your phone has 100% battery power, you will not receive charging notification Some people mean charging, while others mean having external capabilities, whether 100% I mix them together, and if there are any conditions, I return to truth

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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>