This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Qt Android Notifier#

Demonstrates calling Java code from Qt in an Android application.


This example demonstrates how to add a custom Java class to an Android application, and how to call it using the JNI convenience APIs in Qt.

Click on one of the smiley faces to send a notification in the status bar of the Android screen.

Running the Example#

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

Calling Java Methods from C++ Code#

We define a custom Java class called NotificationClient in the NotificationClient.java file:

In the NotificationClient C++ class header file, notificationclient.h, we declare a simple C++ API to display notifications on an Android device. It consists of a single string property, notification, and a slot, updateAndroidNotification(), that calls the Java code:

class NotificationClient(QObject):

# public
    NotificationClient = explicit(QObject parent = 0)
    def setNotification(notification):
    notification = QString()
# signals
    def notificationChanged():
# private slots
    def updateAndroidNotification():
# private
    m_notification = QString()

We connect the notificationChanged() signal to the updateAndroidNotification() slot to update the notification text when the notification text changes:

m_notification = notification

The updateAndroidNotification() function calls the Java method responsible for sending the notification from the Android platform APIs. First, we construct a Java string jstring from the notification string, then pass the jstring object as a parameter to the notify() method in Java:

def updateAndroidNotification(self):

    javaNotification = QJniObject.fromString(m_notification)

The call to the Java meethod use QJniObject which relies on the Java Native Interface (JNI) APIs to communicate with Java. Also, in the previous snippet, we are passing the app’s context object, which the static Java code can use to tap into the app’s specific properties and APIs.

To make sure our smiley buttons do what they are supposed to, we add the the following code to change the notification text if either of them are clicked:

happyButton.clicked.connect([]() {
    NotificationClient().setNotification("The user is happy!")
sadButton.clicked.connect([]() {
    NotificationClient().setNotification("The user is sad!")

See also

Qt for Android

Example project @ code.qt.io