Search code examples
javawindowsjnabattery

Get Windows Charging Status in Java


I am trying to tell weather or not my windows laptop is charging. I want it to check, and return either a 1 or true if it is charging or a 0 or false if it is not. I am following the instructions at How to get the remaining battery life in a Windows system?, But I can't figure out how to parse the answer and get the charging status. Does anyone have a suggestion?

Edit: I want to be able to type something like boolean battery = getBattery(); and have it return true or false


Solution

  • You can use the getBatteryFlagString() method from the referred source. Or use directly the BatteryFlag and check if it's equal to 8, see getBatteryFlagString for details.

    Something like:

    Kernel32.SYSTEM_POWER_STATUS batteryStatus = new Kernel32.SYSTEM_POWER_STATUS();
    Kernel32.INSTANCE.GetSystemPowerStatus(batteryStatus);
    
    boolean battery = batteryStatus.BatteryFlag==8;