使用dbus.SessionBus()
和DBus建立连接
conn, err := dbus.SessionBus()
if err != nil {
panic(err)
}
通过调用org.freedesktop.Notifications.Notify
方法发送桌面通知
call := conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").Call(
"org.freedesktop.Notifications.Notify", 0,
appName, idNum, icon, title, text, actions, hints, expireTime,
)
if call.Err != nil {
panic(call.Err)
}
Notify
参数解释如下:
appName
显示在锁屏界面的应用程序名字
icon
图标文件路径或名称, 一些常见的图标名称有:
dialog-information
消息或提示对话框dialog-warning
警告对话框dialog-error
错误对话框
title
通知的标题
text
通知的具体内容
expireTime
通知显示的过期时间
完整代码如下
package main
import (
"github.com/godbus/dbus/v5"
"time"
)
func main() {
conn, err := dbus.SessionBus()
if err != nil {
panic(err)
}
// 发送通知
appName := "My Application"
idNum := uint32(0)
icon := "" // 图标文件路径或名称
title := "Notification Title"
text := "This is the notification message."
actions := []string{} // 可选操作列表
hints := map[string]dbus.Variant{} // 可选附加信息字典
expireTime := int32(time.Now().Unix() + 5) // 过期时间,单位秒
call := conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").Call(
"org.freedesktop.Notifications.Notify", 0,
appName, idNum, icon, title, text, actions, hints, expireTime,
)
if call.Err != nil {
panic(call.Err)
}
}