app.power - 电源与电池 API
电池状态、电源信息和系统运行时间。
方法
app.power.battery()
获取电池信息。
返回值: table|nil - 台式机返回 nil
返回字段:
level(number) - 电量百分比(0-100)isCharging(boolean) - 是否充电中currentCapacity(number) - 当前容量 (mAh)maxCapacity(number) - 最大容量 (mAh)cycleCount(number, 可选) - 充电循环次数health(number, 可选) - 电池健康度百分比(0-100)temperature(number, 可选) - 电池温度(摄氏度)
local bat = app.power.battery()
if bat then
app.log.info("电量: " .. bat.level .. "%")
app.log.info("充电: " .. tostring(bat.isCharging))
if bat.health then
app.log.info("健康度: " .. string.format("%.1f%%", bat.health))
end
else
app.log.info("无电池(台式机)")
end
app.power.isOnAC()
检查是否使用外接电源。
返回值: boolean
if app.power.isOnAC() then
app.log.info("使用外接电源")
end
app.power.timeRemaining()
获取电池剩余时间。
返回值: number - 剩余分钟数
-1= 正在计算-2= 外接电源
local time = app.power.timeRemaining()
if time > 0 then
app.log.info("剩余 " .. math.floor(time) .. " 分钟")
elseif time == -1 then
app.log.info("正在估算...")
end
app.power.thermalState()
获取系统热状态。
返回值: string - "nominal", "fair", "serious", "critical", "unknown"
local state = app.power.thermalState() -- "nominal"
app.power.uptime()
获取系统运行时间。
返回值: number - 秒数
local up = app.power.uptime()
local hours = math.floor(up / 3600)
local mins = math.floor((up % 3600) / 60)
app.log.info("运行时间: " .. hours .. " 小时 " .. mins .. " 分钟")
事件监听
app.power.watch(event, callback)
监听电源状态变化事件。
参数:
event(string) - 事件名称(目前仅支持"powerSourceChanged")callback(function) - 回调函数,接收事件表:isOnAC(boolean) - 是否使用外接电源batteryLevel(number) - 当前电量百分比(0-100),无电池时为 -1
返回值: string, error - watcher 句柄 ID
app.power.watch("powerSourceChanged", function(e)
if e.isOnAC then
app.log.info("已接入外接电源")
else
app.log.info("使用电池,当前电量: " .. e.batteryLevel .. "%")
end
end)
app.power.stopAllWatchers()
停止当前插件注册的所有电源事件监听器。
返回值: boolean
app.power.stopAllWatchers()
app.power.listWatchers()
列出当前插件已注册的电源事件监听器。
返回值: array<table> - 每项包含:
id(string) - watcher 句柄 IDevent(string) - 监听的事件名称
local watchers = app.power.listWatchers()
for _, w in ipairs(watchers) do
app.log.info(w.id .. " -> " .. w.event)
end
示例
电池状态报告
function MyPlugin:handleBatteryReport(context)
local bat = app.power.battery()
if not bat then
app.dialog.alert("电池", "当前设备没有电池")
return
end
local info = string.format(
"电量: %.0f%%\n充电: %s\n循环: %s\n健康: %s\n温度: %s\n剩余: %s",
bat.level,
bat.isCharging and "是" or "否",
bat.cycleCount and tostring(bat.cycleCount) or "N/A",
bat.health and string.format("%.1f%%", bat.health) or "N/A",
bat.temperature and string.format("%.1f°C", bat.temperature) or "N/A",
app.power.timeRemaining() > 0
and math.floor(app.power.timeRemaining()) .. " 分钟"
or "外接电源"
)
app.dialog.alert("电池状态", info)
end