桌面通知程序 - Arch Linux 中文维基

跳至內容

# 桌面通知程序

出自 Arch Linux 中文维基

相關文章

- GTK
- Libcanberra

翻譯狀態：

- 本文（或部分內容）譯自 Desktop notifications，最近一次同步於 2024-10-20，若英文版本有所更改，則您可以幫助同步與翻譯更改的內容。
- 您可以在 ArchWiki 的對應頁面找到本文翻譯的原始修訂歷史。
- 本文可能與英文原文存在出入。

本文或本節需要翻譯。要貢獻翻譯，請訪問簡體中文翻譯團隊。

附註： 本文的翻譯不完全。（在 Talk:桌面通知程序# 中討論）

本文或本章節的語言、語法或風格需要改進。參考：幫助:風格

原因：中文與英文之間沒有空格，部分標點符號使用不正確，影響閱讀體驗。（在Talk:桌面通知程序討論）

桌面通知是種很小的被動彈出對話框，以異步方式通知用戶特定事件。

## Libnotify

Libnotify 是桌面通知規範的實現，它為 GTK 和 Qt 應用程式提供支持，並且獨立於桌面：它已經被許多開源應用程式（如 Evolution 和 Pidgin）使用。可以通過 libnotify包 安裝。

要使用 libnotify，您必須安裝通知伺服器。

## 通知伺服器

### 內置通知

Cinnamon, Deepin, Enlightenment, GNOME, GNOME Flashback 和 KDE 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 Daemon — LXQt的通知服務。

  https://github.com/lxde/lxqt-notificationd || lxqt-notificationd包

- mako — 適用於Wayland的輕量級通知守護程序;它目前在Sway和 river包上運行。

  https://github.com/emersion/mako || mako包

- MATE Notification Daemon — MATE的通知服務。

  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 Daemon — Xfce的通知服務

  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

- 依賴: libnotify包包

    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.'

- Dependency: glib2包

    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

- Dependency: libnotify包
- Makedependency: go-notify-gitAUR[損壞的連結：package not found]
- Build with: `go build hello_world.go`
- (Or run with: `go run hello_world.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

- Makedependency: haskell-fdo-notify包
- Build with: `ghc -dynamic hello_world`

    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

- Dependencies: notify-sharp-3AUR, ironpythonAUR
- Run with: `ipy hello_world.py`

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

- Dependencies: libnotify包, gjs包

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

- Dependencies: nodejs包, node-dbus-notifier

    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

- Dependency: lua-lgi-gitAUR

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

- Dependencies: libnotify包, lua-lgi-gitAUR

    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

- Dependency: libnotify包
- Makedependency: fpc包, libnotify binding
- Build with: `fpc hello_world`

    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

- Dependencies: libnotify包, perl-glib-object-introspection包

    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

- Dependencies: perl-net-dbus包

    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

- Dependency: python-gobject包

    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)

- Dependencies: libnotify包, python-gobject包

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

- Dependency: python-dbus包

    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

- Dependencies: libnotify包, ruby-gir_ffiAUR[損壞的連結：package not found]

    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

## 提示和技巧

### 替換之前的通知

如果通知的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服務文件時，會導致問題。例如，同時安裝了dunst包和 mako包，在沒有明確指定伺服器時，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服務的多個通知伺服器中所述選擇要使用的服務來解決問題。

## 另請參閱

- Libnotify Reference Manual[失效連結 2024-07-30 ⓘ]
- C example (archived version)
- Python notification examples
- Python notify example (french article)

分類：​

- X 伺服器
- 通知
- 開發
- 軟體列表
- 使用「模板:風格」標記的頁面或章節
- 包含損壞的軟體包連結的頁面
- 使用「模板:Remove」標記的章節
- 包含失效連結的頁面

隱藏分類：​

- 使用「模板:Translateme」標記的頁面或章節

桌面通知程序
新增話題