Sur cette page

Qt pour Android Notifier

Démonstration de l'appel de code Java à partir de Qt dans une application Android.

Cet exemple montre comment ajouter une classe Java personnalisée à une application Android et comment l'appeler à l'aide des API de commodité JNI dans Qt.

Cliquez sur l'un des smileys pour envoyer une notification dans la barre d'état de l'écran Android.

Exécution de l'exemple

Pour exécuter l'exemple à partir de Qt Creatorouvrez le mode Welcome et sélectionnez l'exemple à partir de Examples. Pour plus d'informations, voir Qt Creator: Tutoriel : Construire et exécuter.

Appel de méthodes Java à partir du code C

Nous définissons une classe Java personnalisée appelée NotificationClient dans le fichier 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();
        }
    }
}

Dans le fichier d'en-tête de la classe C++ NotificationClient, notificationclient.h, nous déclarons une API C++ simple pour afficher les notifications sur un appareil Android. Elle se compose d'une propriété de chaîne unique, notification, et d'un slot, updateAndroidNotification(), qui appelle le code Java :

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

Nous connectons le signal notificationChanged() au slot updateAndroidNotification() pour mettre à jour le texte de la notification lorsque le texte notification change :

    m_notification = notification;
    emit notificationChanged();

La fonction updateAndroidNotification() appelle la méthode Java responsable de l'envoi de la notification à partir des API de la plateforme Android. Tout d'abord, nous construisons une chaîne Java jstring à partir de la chaîne de notification, puis nous passons l'objet jstring comme paramètre à la méthode notify() en Java :

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

L'appel à la méthode Java utilise QJniObject qui s'appuie sur les API de l'interface native Java (JNI) pour communiquer avec Java. De plus, dans l'extrait précédent, nous transmettons l'objet contextuel de l'application, que le code Java statique peut utiliser pour accéder aux propriétés et API spécifiques de l'application.

Pour nous assurer que nos boutons smiley font ce qu'ils sont censés faire, nous ajoutons le code suivant pour modifier le texte de notification si l'un d'entre eux est cliqué :

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

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

Exemple de projet @ code.qt.io

Voir aussi Qt pour Android.

© 2026 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.