En esta página

Ejemplo de notificación de Qt para HarmonyOS

Envía una notificación desde una aplicación Qt en HarmonyOS.

El ejemplo solicita al usuario que permita las notificaciones para la aplicación. A continuación, envía una notificación con el título y el texto introducidos en su ventana. Utiliza el módulo « @ohos.notificationManager » de la plataforma.

Los controladores de botones transfieren la tarea al hilo de JS. El título y el texto se recogen en el hilo de Qt como un ` QJsonObject`:

QObject::connect(
    allowNotificationsButton, &QPushButton::clicked, &window,
    [statusLabel]() {
        statusLabel->clear();
        QHarmonyApplication::runOnJsThread(
            [statusLabel = QPointer<QLabel>(statusLabel)](QHarmonyJsContext &jsContext) {
                askUserToAllowNotifications(QHarmonyAppJsContext::fromJsContext(jsContext), statusLabel);
            });
    });
QObject::connect(
    postNotificationButton, &QPushButton::clicked, &window,
    [notificationTitleEdit, notificationTextEdit, statusLabel]() {
        const QJsonObject titleAndText{
            {QStringLiteral("title"), notificationTitleEdit->text()},
            {QStringLiteral("text"), notificationTextEdit->text()},
        };
        statusLabel->clear();
        QHarmonyApplication::runOnJsThread(
            [titleAndText, statusLabel = QPointer<QLabel>(statusLabel)](QHarmonyJsContext &jsContext) {
                postNotification(jsContext, titleAndText, statusLabel);
            });
    });

requestEnableNotification() muestra el cuadro de diálogo de la plataforma en el que el usuario autoriza las notificaciones. Toma el ` UIAbilityContext ` de la capacidad predeterminada, y el cuadro de diálogo se vincula a ese contexto:

void askUserToAllowNotifications(QHarmonyAppJsContext &appJsContext, QPointer<QLabel> statusLabel)
{
    const QString asyncCallName = QStringLiteral("requestEnableNotification()");
    Napi::Env env(appJsContext.env());
    Napi::Object notificationManagerModule(env, appJsContext.tryImportModule(notificationManagerModuleName));
    if (notificationManagerModule.IsEmpty()) {
        showFailureInLabel(statusLabel, asyncCallName, QStringLiteral("no notification manager module"));
        return;
    }

    Napi::Object ability(env, appJsContext.defaultAbility());
    if (ability.IsEmpty()) {
        showFailureInLabel(statusLabel, asyncCallName, QStringLiteral("no ability to request from"));
        return;
    }

    try {
        auto abilityContext = ability.Get("context").As<Napi::Object>();
        auto requestEnableNotificationFunc = notificationManagerModule.Get("requestEnableNotification").As<Napi::Function>();
        auto requestEnableNotificationPromise = requestEnableNotificationFunc.Call(notificationManagerModule, {abilityContext}).As<Napi::Object>();
        attachPromiseHandlersReportingStatusInLabel(requestEnableNotificationPromise, asyncCallName, statusLabel);
    } catch (const Napi::Error &error) {
        showFailureInLabel(statusLabel, asyncCallName, QString::fromUtf8(error.what()));
    }
}

publish() recibe una solicitud de notificación, que la tarea crea en el hilo de JS. El tipo de contenido procede de la enumeración « ContentType » del módulo. El título y el texto se asignan desde « QJsonObject » mediante « QtHarmony::mapQJsonObjectToJsObject()»:

void postNotification(QHarmonyJsContext &jsContext, const QJsonObject &titleAndText, QPointer<QLabel> statusLabel)
{
    const QString asyncCallName = QStringLiteral("publish()");
    Napi::Env env(jsContext.env());
    Napi::Object notificationManagerModule(env, jsContext.tryImportModule(notificationManagerModuleName));
    if (notificationManagerModule.IsEmpty()) {
        showFailureInLabel(statusLabel, asyncCallName, QStringLiteral("no notification manager module"));
        return;
    }

    try {
        auto basicTextContentType = notificationManagerModule.Get("ContentType").As<Napi::Object>().Get("NOTIFICATION_CONTENT_BASIC_TEXT");
        Napi::Object jsTitleAndText(env, QtHarmony::mapQJsonObjectToJsObject(env, titleAndText));

        auto notificationContent = Napi::Object::New(env);
        notificationContent.Set("notificationContentType", basicTextContentType);
        notificationContent.Set("normal", jsTitleAndText);
        auto notificationRequest = Napi::Object::New(env);
        notificationRequest.Set("content", notificationContent);

        auto publishFunc = notificationManagerModule.Get("publish").As<Napi::Function>();
        auto publishPromise = publishFunc.Call(notificationManagerModule, {notificationRequest}).As<Napi::Object>();
        attachPromiseHandlersReportingStatusInLabel(publishPromise, asyncCallName, statusLabel);
    } catch (const Napi::Error &error) {
        showFailureInLabel(statusLabel, asyncCallName, QString::fromUtf8(error.what()));
    }
}

Ambas llamadas devuelven una promesa. Los controladores asociados a la promesa informan del resultado en la ventana. Envían el texto al hilo de Qt mediante QNativeInterface::QHarmonyApplication::runOnQtThread(). Pasan un QPointer a la etiqueta de estado, que se creó en el hilo de Qt. El functor enviado comprueba el QPointer antes de actualizar la etiqueta:

void showStatusInLabel(QPointer<QLabel> statusLabel, QString text)
{
    QHarmonyApplication::runOnQtThread(
        [statusLabel, text]() {
            if (statusLabel)
                statusLabel->setText(text);
        });
}

void showFailureInLabel(QPointer<QLabel> statusLabel, const QString &asyncCallName, const QString &errorText)
{
    showStatusInLabel(statusLabel, QStringLiteral("%1 failed: %2").arg(asyncCallName, errorText));
}

void attachPromiseHandlersReportingStatusInLabel(Napi::Object asyncCallPromise, const QString &asyncCallName, QPointer<QLabel> statusLabel)
{
    asyncCallPromise.Get("then").As<Napi::Function>().Call(
        asyncCallPromise,
        {
            Napi::Function::New(
                asyncCallPromise.Env(),
                [statusLabel, asyncCallName](const Napi::CallbackInfo &) {
                    showStatusInLabel(statusLabel, QStringLiteral("%1 succeeded").arg(asyncCallName));
                }),
            Napi::Function::New(
                asyncCallPromise.Env(),
                [statusLabel, asyncCallName](const Napi::CallbackInfo &info) {
                    showFailureInLabel(statusLabel, asyncCallName, QString::fromStdString(info[0].ToString()));
                }),
        });
}

La ventana también muestra un error que lanza una llamada antes de que exista su promesa, así como la falta de un módulo o una capacidad.

Ejecución del ejemplo

Pulsa Allow notifications y permite las notificaciones en el cuadro de diálogo. A continuación, pulsa Post notification. Mientras las notificaciones no estén permitidas, publish() falla con un error de «Notificación desactivada», que se muestra en la ventana. La solicitud utiliza el ID de notificación predeterminado, por lo que volver a enviarla actualiza la notificación en lugar de añadir otra nueva.

Proyecto de ejemplo en @code.qt.io

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