2009-07-21 204 views
5

我正在开发一个应用程序,用于监控笔记本电脑的电源是否存在。如果有电力削减或恢复,它会通过电子邮件将我私密化。它也将通过电子邮件进行应用程序监视和控制(基本上是通过电子邮件从我的办公室控制笔记本电脑)。我完成了电子邮件接口,但我不知道如何监控来自java的电源/电池电源。从java监控笔记本电脑或笔记本电脑电源

如果有任何可以给这个指针,这将是很大的帮助。

在此先感谢....

+1

这将有助于了解平台(OS),因为这可能是平台特定的。 – jsight 2009-07-21 17:08:06

+0

只是好奇你为什么用这个动词亲密?这听起来很奇怪。你的意思是使用另一个词或是某种电子邮件API? – Victor 2009-07-21 17:57:38

回答

5

您可能已经解决了这个问题,但对于其他人 - 你可以做到这一点亚当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; 
} 

也可以简单脚本直接返回真/假或任何适合。

0

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

2

在Linux上,你可以用的/ proc/ACPI /电池/

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

相关问题