Showing Local Notifications in Qt on Android, iOS, Linux, Windows and MacOS


Tags: , ,

Apparently, Qt does not provide a way to show local notifications with LGPL license. This is the only thing that I found: Qt Application Manager. So I developed something for myself and placed a few lines of code in my collection here: https://github.com/carlonluca/lqtutils (more info). The entire implementation does not require Java for Android, it is entirely written in C/C++.

How to Use

This is an example:

#ifdef Q_OS_ANDROID
    lqt::AndroidSystemNotification notification;
    notification.set_icon(QImage(":/icon.png"));
    notification.set_activityClass(QSL("org.qtproject.qt.android.bindings.QtActivity"));
#else
    lqt::SystemNotification notification;
#endif
    notification.set_appName(qApp->applicationName());
    notification.set_title(tr("Flashbacks available"));
    notification.set_message(tr("You have %1 memories taken in %2 years for today. Have a look!").arg(photos).arg(years));
    notification.set_openApp(true);
    notification.send();

Android requires the activity class, so that the system knows what to launch when the notification is selected.

Linux

For Linux, dbus is being used. KDE and GNOME, at least, should provide notifications though org.freedesktop.Notifications. This means your app will have to link to the Qt D-Bus module.

MacOS/iOS

For MacOS and iOS I used the UserNotifications module. In this case, you’ll also need to request the permission, through:

static void lqt::AppleSystemNotification::requestPermission(std::function<void(bool)> callback);

Windows

On Windows, Shell_NotifyIcon is used. This should, for example, show a notification with a red square as the icon:

QImage icon(32, 32, QImage::Format_RGB32);
icon.fill(Qt::red);
lqt::SystemNotification notification;
notification.set_icon(icon);
notification.set_title("Title");
notification.set_message("Message");
notification.set_replacesId(21);
notification.set_timeout(10000);
notification.send();

Note that:

  • icon must be 16×16 or 32×32 RGB32 on Windows;
  • timeout is valid on Windows only for 2000 and XP.

Android

For Android, use the lqt::AndroidSystemNotification object. Remember to set the class to instantiate when pressed:

notification.set_activityClass(QSL("org.qtproject.qt.android.bindings.QtActivity"));

Please note that I did not implement all the functionalities for each platform. You can send a pull request if you want to add something.
Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *