app.notification - 系统通知 API
发送 macOS 系统通知。
方法
app.notification.show(title, message)
显示系统通知。
参数:
title(string) - 通知标题message(string) - 通知内容
返回值: boolean - 是否成功
app.notification.show("完成", "文件处理完成")
通知观察(需 notification.observe 权限)
跨进程通知,可监听系统和其他应用的通知。
app.notification.observe(name, callback)
监听分布式通知。
参数:
name(string) - 通知名称callback(function) - 回调函数function(name, userInfo?)
返回值: string, error - 观察者 ID(用于取消观察)
local id, err = app.notification.observe("com.example.dataChanged", function(name, info)
app.log.info("收到通知: " .. name)
if info and info.count then
app.log.info("数据量: " .. info.count)
end
end)
app.notification.unobserve(id)
取消监听通知。
参数:
id(string) -observe返回的观察者 ID
返回值: boolean, error
local ok, err = app.notification.unobserve(observerId)
app.notification.unobserveAll()
取消所有通知监听。
返回值: boolean
app.notification.unobserveAll()
app.notification.post(name, userInfo?)
发送分布式通知(跨进程)。
参数:
name(string) - 通知名称userInfo(table, 可选) - 附加数据(支持 string/number/boolean/table)
返回值: boolean, error
app.notification.post("com.example.dataChanged", {
count = 42,
source = "MyPlugin"
})
示例
操作完成通知
function MyPlugin:handleConvert(context)
local files = context.selectedFiles
local success = 0
for _, file in ipairs(files) do
if self:convertFile(file) then
success = success + 1
end
end
app.notification.show("转换完成", "成功转换 " .. success .. "/" .. #files .. " 个文件")
end
错误通知
function MyPlugin:handleUpload(context)
local ok, err = self:uploadFiles(context.selectedFiles)
if ok then
app.notification.show("上传成功", "文件已上传到服务器")
else
app.notification.show("上传失败", err or "未知错误")
end
end
跨插件通信
-- 插件 A:发送通知
function PluginA:handleSendData(context)
local data = self:processFiles(context.selectedFiles)
app.notification.post("com.myplugin.dataReady", {
result = data,
timestamp = os.time()
})
end
-- 插件 B:接收通知
function PluginB:init()
self.observerId = app.notification.observe("com.myplugin.dataReady", function(name, info)
if info and info.result then
self:handleReceivedData(info.result)
end
end)
end
function PluginB:cleanup()
if self.observerId then
app.notification.unobserve(self.observerId)
end
end
注意事项
- 权限:
show首次使用需要用户授权通知权限 - 频率:避免短时间内发送大量通知
- 内容:标题和内容过长会被截断
- 观察者限制:每个插件最多注册 50 个观察者
- 权限分离:
show为 L0(始终可用),observe/unobserve/post为 L1(需在 manifest 中声明notification.observe) - 跨进程:userInfo 仅支持基础类型(string/number/boolean/table)