windows 如何在Windows系统中获得剩余电池寿命?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3434719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:00:01  来源:igfitidea点击:

How to get the remaining battery life in a Windows system?

javawindows

提问by suresh

I need to get the remaining battery life in a Windows system. How can I do it?

我需要在 Windows 系统中获得剩余的电池寿命。我该怎么做?

回答by BalusC

I assume you're talking about a laptop. No such API exist in Standard Java SE API. This information is available in the operating system platform native API only. You would need at least JNIor JNA(JavaWorld article)to be able to communicate with platform native API.

我假设你在谈论一台笔记本电脑。标准 Java SE API 中不存在此类 API。此信息仅在操作系统平台本机 API 中可用。您至少需要JNIJNA (JavaWorld 文章)才能与平台原生 API 进行通信。

In Windows, you'd like to hook on SYSTEM_POWER_STATUSstructure. It offers among others the BatteryLifePercentproperty which may be of your interest. I found a helpful JNA based code snippet in an old forums.sun.com topic which is currently not available anymore. So the credit actually goes to the Author Whose Name Shall Not Be Known.

在 Windows 中,您希望挂钩SYSTEM_POWER_STATUS结构。它提供BatteryLifePercent了您可能感兴趣的财产。我在一个旧的 forums.sun.com 主题中找到了一个有用的基于 JNA 的代码片段,该主题当前不再可用。因此,功劳实际上归功于其姓名不得为人所知的作者。

To get it to work, first drop jna.jarin the classpath and then copy the following class unmodified into your project:

要使其正常工作,请先jna.jar放入类路径,然后将以下未修改的类复制到您的项目中:

package com.example;

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

    /**
     * @see http://msdn2.microsoft.com/en-us/library/aa373232.aspx
     */
    public class SYSTEM_POWER_STATUS extends Structure {
        public byte ACLineStatus;
        public byte BatteryFlag;
        public byte BatteryLifePercent;
        public byte Reserved1;
        public int BatteryLifeTime;
        public int BatteryFullLifeTime;

        @Override
        protected List<String> getFieldOrder() {
            ArrayList<String> fields = new ArrayList<String>();
            fields.add("ACLineStatus");
            fields.add("BatteryFlag");
            fields.add("BatteryLifePercent");
            fields.add("Reserved1");
            fields.add("BatteryLifeTime");
            fields.add("BatteryFullLifeTime");
            return fields;
        }

        /**
         * The AC power status
         */
        public String getACLineStatusString() {
            switch (ACLineStatus) {
                case (0): return "Offline";
                case (1): return "Online";
                default: return "Unknown";
            }
        }

        /**
         * The battery charge status
         */
        public String getBatteryFlagString() {
            switch (BatteryFlag) {
                case (1): return "High, more than 66 percent";
                case (2): return "Low, less than 33 percent";
                case (4): return "Critical, less than five percent";
                case (8): return "Charging";
                case ((byte) 128): return "No system battery";
                default: return "Unknown";
            }
        }

        /**
         * The percentage of full battery charge remaining
         */
        public String getBatteryLifePercent() {
            return (BatteryLifePercent == (byte) 255) ? "Unknown" : BatteryLifePercent + "%";
        }

        /**
         * The number of seconds of battery life remaining
         */
        public String getBatteryLifeTime() {
            return (BatteryLifeTime == -1) ? "Unknown" : BatteryLifeTime + " seconds";
        }

        /**
         * The number of seconds of battery life when at full charge
         */
        public String getBatteryFullLifeTime() {
            return (BatteryFullLifeTime == -1) ? "Unknown" : BatteryFullLifeTime + " seconds";
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("ACLineStatus: " + getACLineStatusString() + "\n");
            sb.append("Battery Flag: " + getBatteryFlagString() + "\n");
            sb.append("Battery Life: " + getBatteryLifePercent() + "\n");
            sb.append("Battery Left: " + getBatteryLifeTime() + "\n");
            sb.append("Battery Full: " + getBatteryFullLifeTime() + "\n");
            return sb.toString();
        }
    }

    /**
     * Fill the structure.
     */
    public int GetSystemPowerStatus(SYSTEM_POWER_STATUS result);
}

Here's how you can use it, e.g. in your main()method:

以下是您如何使用它,例如在您的main()方法中:

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

System.out.println(batteryStatus); // Shows result of toString() method.

This prints successfully the following at my Latitude E5500:

这在我的 Latitude E5500 上成功打印了以下内容:

ACLineStatus: Online
Battery Flag: High, more than 66 percent
Battery Life: 100%
Battery Left: Unknown
Battery Full: Unknown

And after plugging off the AC for 10 minutes:

并在关闭交流电 10 分钟后:

ACLineStatus: Offline
Battery Flag: High, more than 66 percent
Battery Life: 82%
Battery Left: 2954 seconds
Battery Full: Unknown

(no, no bad battery, I am just compiling a movie and continuously transferring over wifi right now ;) )

(不,没有坏电池,我现在只是在编译一部电影并不断通过 wifi 传输;))