Here's code that works on Windows by using the SYSTEM_POWER_STATUS
structure.
Note that you need to add jna
to your (Maven) dependencies for this to work.
import java.util.ArrayList;
import java.util.List;
import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.win32.StdCallLibrary;
public interface Kernel32 extends StdCallLibrary
{
public Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("Kernel32",
Kernel32.class);
public class SYSTEM_POWER_STATUS extends Structure
{
public byte ACLineStatus;
@Override
protected List<String> getFieldOrder()
{
ArrayList<String> fields = new ArrayList<String>();
fields.add("ACLineStatus");
return fields;
}
public boolean isPlugged()
{
return ACLineStatus == 1;
}
}
public int GetSystemPowerStatus(SYSTEM_POWER_STATUS result);
}
In your code call it like this:
Kernel32.SYSTEM_POWER_STATUS batteryStatus = new Kernel32.SYSTEM_POWER_STATUS();
Kernel32.INSTANCE.GetSystemPowerStatus(batteryStatus);
System.out.println(batteryStatus.isPlugged());
Result:
true if charger is plugged in false otherwise
This has been derived off BalsusC's answer.