桌面通知程序

来自 Arch Linux 中文维基
(重定向自Desktop notifications

本文或本节需要翻译。要贡献翻译,请访问简体中文翻译团队

附注: 本文的翻译不完全。(在 Talk:桌面通知程序# 中讨论)

本文或本章节的语言、语法或风格需要改进。参考:帮助:风格

原因:中文与英文之间没有空格,部分标点符号使用不正确,影响阅读体验。(在Talk:桌面通知程序讨论)

桌面通知是种很小的被动弹出对话框,以异步方式通知用户特定事件。

Libnotify[编辑 | 编辑源代码]

Libnotify 是桌面通知规范的实现,它为 GTKQt应用程序提供支持,并且独立于桌面:它已经被许多开源应用程序(如 EvolutionPidgin)使用。可以通过libnotify软件包安装。

要使用 libnotify,您必须安装通知服务器

通知服务器[编辑 | 编辑源代码]

内置通知[编辑 | 编辑源代码]

Cinnamon, Deepin, Enlightenment, GNOME, GNOME FlashbackKDE Plasma 使用自己的实现来显示通知,并且无法替换。他们的通知服务器在登录时自动启动,以通过 DBus 接收来自应用程序的通知。

独立通知[编辑 | 编辑源代码]

在其他桌面环境中,需要使用自动启动选项启动通知服务器。 或者,通过将通知服务器作为 D-Bus的服务,通知服务器可以在第一次调用时自动启动。大多数通知服务器已经在/usr/share/dbus-1/services目录中。对于某些实现,例如 notification-daemon包,需要在用户 D-Bus 服务目录 ($XDG_DATA_HOME/dbus-1/services) 中手动创建一个服务:

org.freedesktop.Notifications.service
[D-BUS Service]
Name=org.freedesktop.Notifications
Exec=/usr/lib/notification-daemon-1.0/notification-daemon

每当应用程序通过向 org.freedesktop.Notifications发送信号来发送通知时,如果他尚未激活,则 D-Bus 将激活/usr/lib/notification-daemon-1.0/notification-daemon

您还可以选择以下实现之一:

  • Deadd Notification Center — 通知中心受Dunst启发的一个通知守护进程。
https://github.com/phuhl/linux_notification_center || deadd-notification-centerAUR
  • Dunst — 适用于 Linux 的极简通知守护进程,旨在很好地适应 dwm等极简窗口管理器。自 1.6 n版本起包括对 Wayland 的支持。
https://dunst-project.org/ || dunst
  • fnott — 键盘驱动的轻量级 Wayland 通知守护程序,适用于基于 wlroots 的合成器。
https://codeberg.org/dnkl/fnott || fnott
  • LXQt Notification DaemonLXQt的通知服务。
https://github.com/lxde/lxqt-notificationd || lxqt-notificationd
  • mako — 适用于Wayland的轻量级通知守护程序;它目前在Swayriver上运行。
https://github.com/emersion/mako || mako
  • MATE Notification DaemonMATE的通知服务。
https://github.com/mate-desktop/mate-notification-daemon/ || mate-notification-daemon
  • Notification Daemon — 最初的通知服务。
https://gitlab.gnome.org/Archive/notification-daemon || notification-daemon
你可以通过/usr/lib/notification-daemon-1.0/notification-daemon手动运行它
  • Notify OSD — Unity的通知服务.
https://launchpad.net/notify-osd || notify-osd
  • sandsmark-notificationd — 可以静音的最小化通知守护程序
https://github.com/sandsmark/sandsmark-notificationd || sandsmark-notificationd-gitAUR[损坏的链接:package not found]
  • statnot — 小巧轻便的通知守护进程,可以将通知输出到根窗口的标题、stdout 或 FIFO 管道,使其与平铺窗口管理器完美集成。
https://github.com/halhen/statnot || statnotAUR
  • swaync — 用于Sway的简单基于 GTK 的通知守护程序。
https://github.com/ErikReider/SwayNotificationCenter || swaync
  • twmn — 用于平铺窗口管理器的通知系统。
https://github.com/sboli/twmn || twmn-gitAUR
  • wired — 轻量级通知守护进程,具有高度可定制的布局块,用 Rust 编写。
https://github.com/Toqozz/wired-notify || wiredAUR
  • Xfce Notification DaemonXfce的通知服务
https://docs.xfce.org/apps/notifyd/start || xfce4-notifyd
你可以通过{/usr/lib/xfce4/notifyd/xfce4-notifyd手动运行它
提示:要配置 xfce4-notifyd,请运行以下命令:xfce4-notifyd-config.

在编程中的使用[编辑 | 编辑源代码]

这一章节正在考虑移除。

原因: API reference pages are out of scope. (在 ArchWiki talk:Maintenance Team#Dealing with API reference pages 讨论)


您可以通过GObject-Introspection或绑定方式,轻松地使用多种编程语言来编写自己的 libnotify 显示消息,或者您可以简单地使用 bash。

以下示例显示一个简单的 “Hello world” 通知。

Bash[编辑 | 编辑源代码]

hello_world.sh
#!/bin/bash
notify-send 'Hello world!' 'This is an example notification.' --icon=dialog-information
提示:
  • An overview on the available icons can be found in the specification.
  • To send desktop notification to another user, e.g. from a background script running as root:
    # systemd-run --machine=user@.host --user notify-send 'Hello world!' 'This is an example notification.'
hello_world.sh
#!/bin/bash
gdbus call --session \
    --dest=org.freedesktop.Notifications \
    --object-path=/org/freedesktop/Notifications \
    --method=org.freedesktop.Notifications.Notify \
    "" 0 "" 'Hello world!' 'This is an example notification.' \
    '[]' '{"urgency": <1>}' 5000
提示:
  • See org.freedesktop.Notifications.Notify for more details about the D-Bus interface.
  • dbus-send, though being similar to gdbus, does not work because one of the arguments in the method org.freedesktop.Notifications.Notify requires data type variant, which is not supported by dbus-send.

C[编辑 | 编辑源代码]

  • Dependency: glib2
  • Build with: gcc -o hello_world `pkg-config --cflags --libs gio-2.0` hello_world.c
hello_world.c
#include <gio/gio.h>
int main() {
	GApplication *application = g_application_new ("hello.world", G_APPLICATION_FLAGS_NONE);
	g_application_register (application, NULL, NULL);
	GNotification *notification = g_notification_new ("Hello world!");
	g_notification_set_body (notification, "This is an example notification.");
	GIcon *icon = g_themed_icon_new ("dialog-information");
	g_notification_set_icon (notification, icon);
	g_application_send_notification (application, NULL, notification);
	g_object_unref (icon);
	g_object_unref (notification);
	g_object_unref (application);
	return 0;
}
  • Dependency: libnotify
  • Build with: gcc -o hello_world `pkg-config --cflags --libs libnotify` hello_world.c
hello_world.c
#include <libnotify/notify.h>
int main() {
	notify_init ("Hello world!");
	NotifyNotification * Hello = notify_notification_new ("Hello world", "This is an example notification.", "dialog-information");
	notify_notification_show (Hello, NULL);
	g_object_unref(G_OBJECT(Hello));
	notify_uninit();
	return 0;
}
  • Dependency: dbus
  • Build with: gcc -o hello_world $(pkg-config --cflags --libs dbus-1) hello_world.c
hello_world.c
#include <dbus-1.0/dbus/dbus.h>
int main()
{
	DBusConnection *connection = dbus_bus_get(DBUS_BUS_SESSION, 0);
	DBusMessage *message = dbus_message_new_method_call(
		"org.freedesktop.Notifications",
		"/org/freedesktop/Notifications",
		"org.freedesktop.Notifications",
		"Notify");
	DBusMessageIter iter[4];
	dbus_message_iter_init_append(message, iter);
	char *application = "hello.world";
	dbus_message_iter_append_basic(iter, 's', &application);
	unsigned id = 0;
	dbus_message_iter_append_basic(iter, 'u', &id);
	char *icon = "dialog-information";
	dbus_message_iter_append_basic(iter, 's', &icon);
	char *summary = "Hello world!";
	dbus_message_iter_append_basic(iter, 's', &summary);
	char *body = "This is an example notification.";
	dbus_message_iter_append_basic(iter, 's', &body);
	dbus_message_iter_open_container(iter, 'a', "s", iter + 1);
	dbus_message_iter_close_container(iter, iter + 1);
	dbus_message_iter_open_container(iter, 'a', "{sv}", iter + 1);
	dbus_message_iter_open_container(iter + 1, 'e', 0, iter + 2);
	char *urgency = "urgency";
	dbus_message_iter_append_basic(iter + 2, 's', &urgency);
	dbus_message_iter_open_container(iter + 2, 'v', "y", iter + 3);
	enum {LOW, NORMAL, CRITICAL};
	unsigned char level = LOW;
	dbus_message_iter_append_basic(iter + 3, 'y', &level);
	dbus_message_iter_close_container(iter + 2, iter + 3);
	dbus_message_iter_close_container(iter + 1, iter + 2);
	dbus_message_iter_close_container(iter, iter + 1);
	int timeout = 5 * 1000;
	dbus_message_iter_append_basic(iter, 'i', &timeout);
	dbus_connection_send(connection, message, 0);
	dbus_connection_flush(connection);
	dbus_message_unref(message);
	dbus_connection_unref(connection);
}

C++[编辑 | 编辑源代码]

  • Dependency: glibmm
  • Build with: g++ -o hello_world `pkg-config --cflags --libs giomm-2.4` hello_world.cc
hello_world.cc
#include <giomm-2.4/giomm.h>
int main(int argc, char *argv[]) {
	auto Application = Gio::Application::create("hello.world", Gio::APPLICATION_FLAGS_NONE);
	Application->register_application();
	auto Notification = Gio::Notification::create("Hello world");
	Notification->set_body("This is an example notification.");
	auto Icon = Gio::ThemedIcon::create("dialog-information");
	Notification->set_icon (Icon);
	Application->send_notification(Notification);
	return 0;
}
  • Dependency: libnotifymmAUR[损坏的链接:package not found]
  • Build with: g++ -o hello_world `pkg-config --cflags --libs libnotifymm-1.0` hello_world.cc
hello_world.cc
#include <libnotifymm.h>
int main(int argc, char *argv[]) {
	Notify::init("Hello world!");
	Notify::Notification Hello("Hello world", "This is an example notification.", "dialog-information");
	Hello.show();
	return 0;
}

C#[编辑 | 编辑源代码]

  • Dependency: notify-sharp-3AUR
  • Build with: mcs -pkg:notify-sharp-3.0 hello_world.cs
  • Run with: mono hello_world.exe
hello_world.cs
using Notifications;
public class HelloWorld {
	static void Main() {
		var Hello = new Notification();
		Hello.Summary  = "Hello world!";
		Hello.Body     = "This is an example notification.";
		Hello.IconName = "dialog-information";
		Hello.Show();
	}
}

Common Lisp[编辑 | 编辑源代码]

  • Dependency: dbus, death/dbus (from quicklisp)
hello_world.lisp
(defun hello ()
  "send notification with dbus"
  (let ((app_name "hello.world")
        (replaces_id 0)
        (app_icon "dialog-information")
        (summary "hello.world")
        (body "Hello world!")
        (expire_timeout -1))
    (dbus:with-open-bus (bus (dbus:session-server-addresses))
      (dbus:with-introspected-object
          (notif bus "/org/freedesktop/Notifications" "org.freedesktop.Notifications")
        (notif "org.freedesktop.Notifications" "Notify"
               app_name replaces_id app_icon summary body '() '() expire_timeout)))))

(hello)

Crystal[编辑 | 编辑源代码]

  • Dependency: woodruffw/notify.cr (from shards)
  • Build with: shards build
hello_world.fs
require "notify"
notifier = Notify.new
notifier.notify "Hello", body: "World!"

F#[编辑 | 编辑源代码]

  • Dependency: notify-sharp-3AUR
  • Makedependency: dotnet-sdk
  • Build with: fsharpc -r:notify-sharp.dll -I:/usr/lib/mono/notify-sharp-3.0/ -I:/usr/lib/mono/gtk-sharp-3.0/ hello_world.fs
  • Run with: mono hello_world.exe
hello_world.fs
open Notifications
let Hello = new Notification()
Hello.Summary  <- "Hello world!"
Hello.Body     <- "This is an example notification."
Hello.IconName <- "dialog-information"
Hello.Show()

Genie[编辑 | 编辑源代码]

  • Dependency: glib2
  • Makedependency: vala
  • Build with: valac --pkg gio-2.0 hello_world.gs
hello_world.gs
uses 
	GLib

init
	var Application = new GLib.Application ("hello.world", GLib.ApplicationFlags.FLAGS_NONE);
	Application.register ();
	var Notification = new GLib.Notification ("Hello world");
	Notification.set_body ("This is an example notification.");
	var Icon = new GLib.ThemedIcon ("dialog-information");
	Notification.set_icon (Icon);
	Application.send_notification (null, Notification);
  • Dependency: libnotify
  • Makedependency: vala
  • Build with: valac --pkg libnotify hello_world.gs
hello_world.gs
uses 
	Notify

init
	Notify.init ("Hello world")
	var Hello=new Notify.Notification ("Hello world!","This is an example notification.","dialog-information")
	Hello.show ()

Go[编辑 | 编辑源代码]

hello_world.go
package main
import ("github.com/mqu/go-notify")

func main() {
	notify.Init("Hello world")
	hello := notify.NotificationNew("Hello World!", "This is an example notification.","dialog-information")
	hello.Show()
}

Groovy[编辑 | 编辑源代码]

  • Dependencies: groovy, java-gnomeAUR
  • Build with: groovyc -cp /usr/share/java/gtk.jar HelloWorld.groovy && jar cfe HelloWorld.jar HelloWorld HelloWorld.class
  • Run with: java -cp /usr/share/groovy/embeddable/groovy-all.jar:/usr/share/java/gtk.jar:HelloWorld.jar HelloWorld or groovy -cp /usr/share/java/gtk.jar HelloWorld.groovy
HelloWorld.groovy
import org.gnome.gtk.*
import org.gnome.notify.*

Gtk.init()
Notify.init("Hello world")
def Hello = new Notification("Hello world!", "This is an example notification.", "dialog-information")
Hello.show()

Haskell[编辑 | 编辑源代码]

hello_world.hs
import DBus.Notify
main = do
         client <- connectSession
         let hello = blankNote { summary="Hello world!",
                                 body=(Just $ Text "This is an example notification."),
                                 appImage=(Just $ Icon "dialog-information") }
         notification <- notify client hello
         return 0

IronPython[编辑 | 编辑源代码]

hello_world.py
import clr
clr.AddReference('notify-sharp')
import Notifications
Hello = Notifications.Notification()
Hello.Summary  = "Hello world!"
Hello.Body     = "This is an example notification."
Hello.IconName = "dialog-information"
Hello.Show()

Java[编辑 | 编辑源代码]

  • Dependency: java-gnomeAUR
  • Makedependency: java-environment
  • Build with: javac -cp /usr/share/java/gtk.jar HelloWorld.java && jar cfe HelloWorld.jar HelloWorld HelloWorld.class
  • Run with: java -cp /usr/share/java/gtk.jar:HelloWorld.jar HelloWorld
HelloWorld.java
import org.gnome.gtk.Gtk;
import org.gnome.notify.Notify;
import org.gnome.notify.Notification;

public class HelloWorld
{
    public static void main(String[] args) {
        Gtk.init(args);
        Notify.init("Hello world");
        Notification Hello = new Notification("Hello world!", "This is an example notification.", "dialog-information");
        Hello.show();
    }
}

JavaScript[编辑 | 编辑源代码]

  • Dependency: gjs
hello_world.js
#!/usr/bin/gjs
const Gio = imports.gi.Gio;
var Application = new Gio.Application ({application_id: "hello.world"});
Application.register (null);
var Notification = new Gio.Notification ();
Notification.set_title ("Hello world");
Notification.set_body ("This is an example notification.");
var Icon = new Gio.ThemedIcon ({name: "dialog-information"});
Notification.set_icon (Icon);
Application.send_notification (null, Notification);
hello_world.js
#!/usr/bin/gjs
const Notify = imports.gi.Notify;
Notify.init ("Hello world");
var Hello=new Notify.Notification ({summary: "Hello world!",
                                    body: "This is an example notification.",
                                    "icon-name": "dialog-information"});
Hello.show ();
hello_world.js
#!/usr/bin/env node
const notifier = require("node-dbus-notifier");

const notify = new notifier.Notify({
  appName: "JavaScript",
  appIcon: "archlinux-logo",
  summary: "Hello world!",
  hints: {
    urgency: 2,
  },
  body: "This is an example notification.",
  timeout: 5000,
});

notify.addAction("Click Me", () => {
  console.log("Click Click");
});

notify.show()
  .then(() => {
    console.log("notify is closed");
  });

JRuby[编辑 | 编辑源代码]

  • Dependencies: java-gnomeAUR, jruby
  • Build with: jrubyc hello_world.rb && jar cfe hello_world.jar hello_world hello_world.class
  • Run with: java -cp /opt/jruby/lib/jruby.jar:hello_world.jar hello_world or jruby hello_world.rb
hello_world.rb
require '/usr/share/java/gtk.jar'
import Java::OrgGnomeGtk::Gtk
import Java::OrgGnomeNotify::Notify
import Java::OrgGnomeNotify::Notification

Gtk.init(nil)
Notify.init("Hello world")
Hello = Notification.new("Hello world!", "This is an example notification.", "dialog-information")
Hello.show

Jython[编辑 | 编辑源代码]

  • Dependencies: java-gnomeAUR, jython
  • Run with: jython -Dpython.path=/usr/share/java/gtk.jar hello_world.py
hello_world.py
from org.gnome.gtk import Gtk
from org.gnome.notify import Notify, Notification
Gtk.init(None)
Notify.init("Hello world")
Hello=Notification("Hello world!", "This is an example notification.", "dialog-information")
Hello.show()

Lua[编辑 | 编辑源代码]

hello_world.lua
#!/usr/bin/lua
lgi = require 'lgi'
Gio = lgi.require('Gio')
Application = Gio.Application.new("hello.world",Gio.ApplicationFlags.FLAGS_NONE);
Application:register();
Notification = Gio.Notification.new("Hello world");
Notification:set_body("This is an example notification.");
Icon = Gio.ThemedIcon.new("dialog-information");
Notification:set_icon(Icon);
Application:send_notification(nil, Notification);
hello_world.lua
#!/usr/bin/lua
lgi = require 'lgi'
Notify = lgi.require('Notify')
Notify.init("Hello world")
Hello=Notify.Notification.new("Hello world","This is an example notification.","dialog-information")
Hello:show()

Nemerle[编辑 | 编辑源代码]

  • Dependency: notify-sharp-3AUR
  • Makedependency: nemerleAUR
  • Build with: ncc -pkg:notify-sharp-3.0 -out:hello_world.exe hello_world.n
  • Run with: mono hello_world.exe
hello_world.n
using Notifications;
public class HelloWorld {
	static Main() : void {
		def Hello = Notification();
		Hello.Summary  = "Hello world!";
		Hello.Body     = "This is an example notification.";
		Hello.IconName = "dialog-information";
		Hello.Show();
	}
}

Pascal[编辑 | 编辑源代码]

hello_world.pas
program	hello_world;
uses	libnotify;
var	hello : PNotifyNotification;
begin
	notify_init(argv[0]);
	hello := notify_notification_new ('Hello world', 'This is an example notification.', 'dialog-information');
	notify_notification_show (hello, nil);
end.

Perl[编辑 | 编辑源代码]

Using libnotify[编辑 | 编辑源代码]

hello_world.pl
#!/usr/bin/perl
use Glib::Object::Introspection;
Glib::Object::Introspection->setup(basename => 'Notify',
                                   version => '0.7',
                                   package => 'Notify');
Notify->init;
my $hello = Notify::Notification->new('Hello world!',
                                      'This is an example notification.',
                                      'dialog-information');
$hello->show;

Using direct D-Bus calls[编辑 | 编辑源代码]

hello_world.pl
#!/usr/bin/perl
use Net::DBus;
my $bus = Net::DBus->session;
my $svc = $bus->get_service('org.freedesktop.Notifications');
my $obj = $svc->get_object('/org/freedesktop/Notifications');
my $id = $obj->Notify('myapp', 0,
                      'dialog-information',
                      'Hello world!',
                      'This is an example notification.',
                      [], {}, 0);

Python[编辑 | 编辑源代码]

hello_world.py
#!/usr/bin/python3
import gi
gi.require_version('Gio', '2.0')
from gi.repository import Gio
Application = Gio.Application.new("hello.world", Gio.ApplicationFlags.FLAGS_NONE)
Application.register()
Notification = Gio.Notification.new("Hello world")
Notification.set_body("This is an example notification.")
Icon = Gio.ThemedIcon.new("dialog-information")
Notification.set_icon(Icon)
Application.send_notification(None, Notification)
hello_world.py
#!/usr/bin/python3
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
Notify.init("Hello world")
Hello = Notify.Notification.new("Hello world", "This is an example notification.", "dialog-information")
Hello.show()
hello_world.py
#!/usr/bin/env python3
import dbus

obj = dbus.SessionBus().get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
obj = dbus.Interface(obj, "org.freedesktop.Notifications")
obj.Notify("", 0, "", "Hello world", "This is an example notification.", [], {"urgency": 1}, 10000)

For the arguments in the method Notify, please refer to the section of org.freedesktop.Notifications.Notify at Desktop Notifications Specification.

Ruby[编辑 | 编辑源代码]

hello_world.rb
#!/usr/bin/ruby
require 'gir_ffi'
GirFFI.setup :Notify
Notify.init("Hello world")
Hello = Notify::Notification.new("Hello world!", "This is an example notification.", "dialog-information")
Hello.show

Rust[编辑 | 编辑源代码]

Using notify-rust.

  • Makedependency: rust
  • Build with: cargo build
  • Run with: target/debug/hello_world or cargo run
Cargo.toml
[package]
name = "hello_world"
version = "0.1.0"

[dependencies]
notify-rust = "^3"
src/main.rs
extern crate notify_rust;
use notify_rust::Notification;
fn main(){
    Notification::new()
        .summary("Hello world")
        .body("This is an example notification.")
        .icon("dialog-information")
        .show().unwrap();
}

Scala[编辑 | 编辑源代码]

  • Dependency: java-gnomeAUR (and scalaAUR)
  • Makedependency: scalaAUR
  • Build with: scalac -cp /usr/share/java/gtk.jar -d HelloWorld.jar HelloWorld.scala
  • Run with: java -cp /usr/share/java/gtk.jar:HelloWorld.jar HelloWorld (or scala -cp /usr/share/java/gtk.jar HelloWorld.scala)
HelloWorld.scala
import org.gnome.gtk._
import org.gnome.notify._

object HelloWorld {
  def main(args: Array[String]) {
    Gtk.init(args)
    Notify.init("Hello world")
    var Hello = new Notification("Hello world!", "This is an example notification.", "dialog-information")
    Hello.show()
  }
}

Vala[编辑 | 编辑源代码]

  • Dependency: glib2
  • Makedependency: vala
  • Build with: valac --pkg gio-2.0 hello_world.vala
hello_world.vala
using GLib;
public class HelloWorld {
	static void main () {
		var Application = new GLib.Application ("hello.world", GLib.ApplicationFlags.FLAGS_NONE);
		Application.register ();
		var Notification = new GLib.Notification ("Hello world");
		Notification.set_body ("This is an example notification.");
		var Icon = new GLib.ThemedIcon ("dialog-information");
		Notification.set_icon (Icon);
		Application.send_notification (null, Notification);
	}
}
  • Dependency: libnotify
  • Makedependency: vala
  • Build with: valac --pkg libnotify hello_world.vala
hello_world.vala
using Notify;
public class HelloWorld {
	static void main () {
		Notify.init ("Hello world");
		var Hello = new Notify.Notification("Hello world!", "This is an example notification.", "dialog-information");
		Hello.show ();
	}
}

Visual Basic .NET[编辑 | 编辑源代码]

  • Dependency: notify-sharp-3AUR
  • Makedependency: mono-basicAUR
  • Build with: vbnc -r:/usr/lib/mono/notify-sharp-3.0/notify-sharp.dll hello_world.vb
  • Run with: mono hello_world.exe
hello_world.vb
Imports Notifications
Public Class Hello
	Public Shared Sub Main
		Dim Hello As New Notification
		Hello.Summary  = "Hello world!"
		Hello.Body     = "This is an example notification."
		Hello.IconName = "dialog-information"
		Hello.Show
	End Sub
End Class

提示和技巧[编辑 | 编辑源代码]

Replace previous notification[编辑 | 编辑源代码]

如果通知的ID已知,则可以替换通知;如果新的通知请求指定了相同的 ID,它将始终替换旧通知。(上面显示的 libnotify 绑定会自动处理此问题。)遗憾的是,notify-send 不会报告此 ID,因此需要替代工具才能在 CLI 上执行此操作。一个功能强大的 CLI 工具是 notify-send.py脚本,它提供 notify-send 语法以及额外的 ID 报告和替换功能。

但是,对于某些通知服务器(例如 Notify-OSD),您可以把string:x-canonical-private-synchronous:的提示与 notify-send结合使用,以达到相同的结果。

例如,要获取通知的显示时间:

while true; do
  date=$(date)
  notify-send "$date" -h string:x-canonical-private-synchronous:my-notification
  sleep 1
done

包含按钮或侦听通知的关闭/单击事件[编辑 | 编辑源代码]

使用notify-send.py脚本,有显示按钮操作或监听通知的默认操作(通常是在用户单击通知时)和关闭操作。当 action-icons 提示设置为 true 并且通知守护程序支持此功能时,按钮将显示图标而不是文本。当相应的事件发生时,脚本会打印操作标识符或命令行的 “close”要监听默认操作 (on-click),必须使用 action-identfier “default”。

按钮上有图标的示例:

notify-send.py "Buttons" "Do you like em?" --hint boolean:action-icons:true --action yes:face-cool no:face-sick

具有D-Bus服务的多个通知服务器[编辑 | 编辑源代码]

#独立通知部分所述,用户可以创建D-Bus服务,以便可以自动启动一个通知服务器。一些实现已经包含D-Bus服务文件。但是,当安装了多个通知服务器并且其中一些附带了D-Bus服务文件时,会导致问题。例如,同时安装了dunstmako,在没有明确指定服务器时,D-Bus会为用户选择一个,此选择不受用户控制。为避免这种情况,您可以通过创建org.freedesktop.Notifications.service文件来覆盖服务 (请参阅 #独立通知)并指向要使用的服务,然后重新启动会话。


Systemd services失败的通知[编辑 | 编辑源代码]

要获得失败服务的通知,请在目标用户上安装并运行 systembus-notify,并按照 systemd#通知失败的单元中给出的说明进行操作,但将failure-notification@模板单元替换为下面的这个:

/etc/systemd/system/failure-notification@.service
[Unit]
Description=Send a notification about a failed systemd unit
After=Graphical.target

[Service]
Type=simple
ExecStart=/usr/bin/dbus-send --system / net.nuetzlich.SystemNotifications.Notify 'string:%i' 'string:Unit failed'

遗憾的是,此解决方案尚不支持设置通知的紧急性或超时,请参阅此问题


故障排除[编辑 | 编辑源代码]

应用程序挂起整整一分钟[编辑 | 编辑源代码]

如果应用程序在尝试显示通知时挂起,可能是因为D-Bus服务错误地发布了通知服务的其可用性。 例如,假设一个用户最近安装了一个需要plasma-workspace的 KDE组件,但该用户仍在运行XFCE。在这种情况下,KDE通知器将被优先考虑,但用户没有运行它。应用程序将在等待服务时挂起,只有在超时后才会回退到xfce4-notifyd

最明显的挂起可能是来自音量指示器滚动调整。

如果您处于这种情况,您应该有两个通知处理程序:

$ find /usr/share/dbus-1/services/ -name '*Notif*'
org.kde.plasma.Notifications.service
org.xfce.xfce4-notifyd.Notifications.service

在这两个应用程序中,一个在 1 分钟超时后经常失败,如journal日志中所示:

# journalctl -g notif
Jul 01 09:40:49 laptop dbus-daemon[866]: [session uid=1000 pid=866] Activating service name='org.freedesktop.Notifications' requested by ':1.193' (uid=1000 pid=5432 comm="/usr/lib/xfce4/panel/wrapper-2.0 /usr/lib/xfce4/pa")
Jul 01 09:41:49 laptop plasma_waitforname[6093]: org.kde.knotifications: WaitForName: Service was not registered within timeout
Jul 01 09:41:49 laptop dbus-daemon[866]: [session uid=1000 pid=866] Activated service 'org.freedesktop.Notifications' failed: Process org.freedesktop.Notifications exited with status 1

按照 #具有D-Bus服务的多个通知服务器中所述选择要使用的服务来解决问题。

另请参阅[编辑 | 编辑源代码]