从java监控笔记本电脑的电池或电源

时间:2009-07-21 16:34:55

标签: java hardware-interface

我正在开发一个监控笔记本电脑电源的应用程序。如果停电或恢复,它将通过电子邮件与我保持联系。它还将通过应用程序监控和控制电子邮件(主要是通过电子邮件从我的办公室控制我的笔记本电脑)。我完成了电子邮件接口,但我不知道如何监控java的电源/电池供电。

如果有人可以给出一些指针,那将会有很大的帮助。

提前致谢....

5 个答案:

答案 0 :(得分:5)

你可能已经解决了这个问题但是对于其他人来说 - 你可以像Adam Crume建议的那样,使用已经编写的脚本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;
}

或者您可以简化脚本以直接返回True / False或任何适合。

答案 1 :(得分:2)

在linux上,您可以使用/ proc / acpi / battery /

答案 2 :(得分:1)

快速谷歌搜索出现java acpi library on sourceforge。自2004年以来尚未更新。

答案 3 :(得分:0)

处理此问题的快速而肮脏的方法是调用本机程序(通过Runtime.exec(...))并解析输出。在Windows上,本机程序可能是使用WMI的VBScript。

答案 4 :(得分:0)

此处使用SYSTEM_POWER_STATUS结构在Windows上运行的代码。

请注意,您需要将jna添加到您的(Maven)依赖项中才能使其正常工作。

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);
}

在您的代码中调用它:

Kernel32.SYSTEM_POWER_STATUS batteryStatus = new Kernel32.SYSTEM_POWER_STATUS();
Kernel32.INSTANCE.GetSystemPowerStatus(batteryStatus);

System.out.println(batteryStatus.isPlugged());

结果:

true if charger is plugged in false otherwise

这是BalsusC's answer的结果。