Monitoring battery or laptop power from java

I am developing an application that monitors the availability of a laptop power source. If there is electricity or restoration, he will intuitively email me. It will also be application monitoring and email control (mainly for managing my laptop from my office via email). I ended up working with email, but I have no idea how to control the power / battery supply from java.

If anyone can give some indication of this, this will be very helpful.

Thanks in advance....

+5
source share
5 answers

, , - , Adam Crume, script battstat.bat Windows XP . :

private Boolean runsOnBattery() {
    try {
        Process proc = Runtime.getRuntime().exec("cmd.exe /c battstat.bat");

        BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(proc.getInputStream()));

        String s;
        while ((s = stdInput.readLine()) != null) {
            if (s.contains("mains power")) {
                return false;
            } else if (s.contains("Discharging")) {
                return true;
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return false;
}

script, True/False - .

+5

linux /proc/acpi/battery/

+2

Google java acpi sourceforge. 2004 .

+1

A quick and dirty way to handle this is to call your own program (via Runtime.exec (...)) and analyze the output. On Windows, the native program may be VBScript, which uses WMI.

0
source

Here is code that runs on Windows using structure SYSTEM_POWER_STATUS.

Note that you need to add jnadependencies in your (Maven) for this.

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 looks 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 was triggered by a response from BalsusC .

0
source

All Articles