Qt for Android Notifier

演示在 Android 应用程序中从 Qt 调用 Java 代码。

本例演示了如何在 Android 应用程序中添加自定义 Java 类,以及如何使用 Qt 中的 JNI 便捷 API 调用 Java 类。

点击其中一个笑脸即可在 Android 屏幕的状态栏中发送通知。

运行示例

要从 Qt Creator,打开Welcome 模式,然后从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行

从 C++ 代码中调用 Java 方法

我们在 NotificationClient.java 文件中定义了一个名为NotificationClient 的自定义 Java 类:

package org.qtproject.example.androidnotifier;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.BitmapFactory;
import android.app.NotificationChannel;

public class NotificationClient
{
    public static void notify(Context context, String message) {
        try {
            NotificationManager m_notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);

            Notification.Builder m_builder;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel notificationChannel;
                notificationChannel = new NotificationChannel("Qt", "Qt Notifier", importance);
                m_notificationManager.createNotificationChannel(notificationChannel);
                m_builder = new Notification.Builder(context, notificationChannel.getId());
            } else {
                m_builder = new Notification.Builder(context);
            }

            Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
            m_builder.setSmallIcon(R.drawable.icon)
                    .setLargeIcon(icon)
                    .setContentTitle("A message from Qt!")
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setColor(Color.GREEN)
                    .setAutoCancel(true);

            m_notificationManager.notify(0, m_builder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在 NotificationClient C++ 类头文件notificationclient.h 中,我们声明了一个简单的 C++ API,用于在 Android 设备上显示通知。它由一个字符串属性notification 和一个调用 Java 代码的槽updateAndroidNotification() 组成:

class NotificationClient : public QObject
{
    Q_OBJECT
public:
    explicit NotificationClient(QObject *parent = 0);

    void setNotification(const QString &notification);
    QString notification() const;

signals:
    void notificationChanged();

private slots:
    void updateAndroidNotification();

private:
    QString m_notification;
};

我们将notificationChanged() 信号连接到updateAndroidNotification() 槽,以便在notification 文本发生变化时更新通知文本:

    m_notification = notification;
    emit notificationChanged();

updateAndroidNotification() 函数调用负责从 Android 平台 API 发送通知的 Java 方法。首先,我们根据通知字符串构建一个 Java 字符串jstring ,然后将jstring 对象作为参数传递给 Java 中的notify() 方法:

void NotificationClient::updateAndroidNotification()
{
    QJniObject javaNotification = QJniObject::fromString(m_notification);
    QJniObject::callStaticMethod<void>(
                    "org/qtproject/example/androidnotifier/NotificationClient",
                    "notify",
                    "(Landroid/content/Context;Ljava/lang/String;)V",
                    QNativeInterface::QAndroidApplication::context(),
                    javaNotification.object<jstring>());
}

对 Java meethod 的调用使用QJniObject ,它依赖 Java 本地接口(JNI)API 与 Java 通信。此外,在前面的代码段中,我们传递了应用程序的上下文对象,静态 Java 代码可以使用该对象来访问应用程序的特定属性和 API。

为了确保我们的笑脸按钮能发挥其应有的作用,我们添加了以下代码,以便在点击其中任何一个按钮时更改通知文本:

    QObject::connect(&happyButton, &QPushButton::clicked, &happyButton, []() {
        NotificationClient().setNotification("The user is happy!");
    });

    QObject::connect(&sadButton, &QPushButton::clicked, &happyButton, []() {
        NotificationClient().setNotification("The user is sad!");
    });

示例项目 @ code.qt.io

另请参阅 Qt for Android

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.