Beispiel für eine Benachrichtigung mit Qt für HarmonyOS
Sendet eine Benachrichtigung aus einer Qt-Anwendung unter HarmonyOS.
Das Beispiel fordert den Benutzer auf, Benachrichtigungen für die Anwendung zuzulassen. Anschließend sendet es eine Benachrichtigung mit dem im Fenster eingegebenen Titel und Text. Dabei wird das Modul „ @ohos.notificationManager “ der Plattform verwendet.
Die Schaltflächen-Handler übergeben die Aufgabe an den JS-Thread. Der Titel und der Text werden im Qt-Thread als „ QJsonObject “ erfasst:
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() zeigt den Plattformdialog an, in dem der Benutzer Benachrichtigungen zulässt. Es übernimmt den ` UIAbilityContext ` der Standardfunktion, und der Dialog wird an diesen Kontext gebunden:
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() Nimmt eine Benachrichtigungsanforderung entgegen, die die Aufgabe im JS-Thread aufbaut. Der Inhaltstyp stammt aus der „ ContentType “-Aufzählung des Moduls. Titel und Text werden aus dem „ QJsonObject “ mit „ QtHarmony::mapQJsonObjectToJsObject()“ zugeordnet:
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()));
}
}Beide Aufrufe geben ein Promise zurück. Die an das Promise angehängten Handler melden das Ergebnis im Fenster. Sie senden den Text mit ` QNativeInterface::QHarmonyApplication::runOnQtThread()` an den Qt-Thread. Sie übergeben ein ` QPointer ` an das Statuslabel, das im Qt-Thread erstellt wurde. Der gesendete Funktor überprüft ` QPointer `, bevor er das Label aktualisiert:
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()));
}),
});
}Das Fenster zeigt außerdem einen Fehler an, der auftritt, wenn ein Aufruf ausgeführt wird, bevor das zugehörige Promise existiert, sowie ein fehlendes Modul oder eine fehlende Funktion.
Ausführen des Beispiels
Drücken Sie „ Allow notifications “ und erlauben Sie Benachrichtigungen im Dialogfeld. Drücken Sie anschließend „ Post notification “. Solange Benachrichtigungen nicht erlaubt sind, schlägt „ publish() “ mit dem Fehler „Notification disabled“ fehl, der im Fenster angezeigt wird. Die Anfrage verwendet die Standard-Benachrichtigungs-ID, sodass ein erneutes Posten die Benachrichtigung aktualisiert, anstatt eine neue hinzuzufügen.
© 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.