How to Send Desktop Notifications under Linux

How to Send Desktop Notifications under Linux

有这个文章是因为,曾经不小心看到了 Arch wiki 里有个神奇的页面, 里面介绍了"回"字的X种写法

然后我在 C+ glib2 这种写法上面翻车了: https://wiki.archlinux.org/title/Desktop_notifications#C

完全按 wiki 来的:

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

结果却非常意外,没有任何通知出现。

但是使用 notify-send hello 却是工作得很正常(后面发现使用 libnotifydbus 的方式也都工作正常)。

当时也就放弃了。后面看到了文档:

Warning: gnome-shell uses desktop files to find extra information (app icon, name) about the sender of the notification. If you don't have a desktop file whose base name matches the application id, then your notification will not show up.

这个 GNOME 的旧文档,反而把事情说得比新文档明白通俗易懂一些。

新版本的文档是这样写的:

https://developer.gnome.org/documentation/tutorials/notifications.html#prerequisites

In order to use notifications in GNOME you will need to:

  • use GApplication or GtkApplication

  • provide a valid desktop file with the same name as your application id

  • ensure that your application can be activated via D-Bus

文档在第二点说明了这个问题。但是没有写得那么容易让人看懂。(如果不提供会发生什么?作为用户,完全不知道,如果这条不满足,通知会直接不显示)

好了,回到最开始的问题, 由于新建 GNOME 应用的时候用的是 g_application_new ("hello.world", G_APPLICATION_FLAGS_NONE);, 因此, application id 为 hello.world, 所以,必须要存在一个名为 hello.world.desktop 的 desktop 文件, 里面至少要有 NameIcon 等.

[Desktop Entry]
Name=GNotification Hello World
Exec=/usr/local/bin/hello.world %U
Icon=hello-world

然后你还要把 hello-world.png 的图标文件 和 hello.world.desktop desktop 文件放在正确的位置.

这样这个通知才能发送出来.

refs

https://wiki.archlinux.org/title/Desktop_notifications

https://gitlab.gnome.org/GNOME/gnome-shell/-/issues/5708

https://github.com/flatpak/xdg-desktop-portal-gtk/pull/394/files