Important: Please read the Qt Code of Conduct -

Creating Java objects under Android

  • I am trying to use QAndroidJniObject to execute some Java code in my Android application, but, unlike the Qt Notifier example provided with Qt, I cannot do even create the class I need.

    NotificationClient class in the Qt Notifier example seems to implement some sort of singleton pattern. It is suitable for me too, but I cannot figure out how the object is created. I have added a logging line to the constructor:

    @public NotificationClient()
    Log.d("AZ", "Created");
    m_instance = this;

    The "Created" message appear in the output in the very beginning, just after "Late-enabling CheckJNI" message. It seems that the constructor is called and the instance is somehow created before running the "main" function of the C++ code.

    Then there is my own program with a test Java class:

    @public class Test extends
    private static Test m_instance;
    public Test()
    Log.d("AZ", "Object created");
    m_instance = this;

    public static int tryTest()
        Log.d("AZ", "Static method called");
        if (m_instance != null) Log.d("AZ", "Instance not null");
        return 100;


    The "main" function has the following lines:

    @jint r = QAndroidJniObject::callStaticMethod<jint>("org/qtproject/example/test/Test", "tryTest");
    qDebug() << r;@

    The output is "Static method called" and then "100", which is OK, but m_instance is null and the "Object created" message never appears, so the constructor is not called. Why is the behaviour different from the Qt Notifier example?

    Next, I have tried to create the object manually:

    @QAndroidJniObject o("org/qtproject/example/test/Test");
    qDebug() << o.isValid();
    jint r = QAndroidJniObject::callStaticMethod<jint>("org/qtproject/example/test/Test", "tryTest");
    qDebug() << r;@

    The result is even stranger. The output is "true" and "0", and there are no logcat messages, so neither constructor nor the "tryTest" static method are actually called, but the object is considered valid, even if it was not actually created. It just does not make any sense.

    Are there any guides to using QAndroidJniObject? The class documentation does not provide any clues.

  • After some extensive search I have finally found how to create Java object on program start: the class should be marked as the program's activity in the "AndroidManifest.xml file". It should be done by editing the XML source itself. I the example I have provided in my original post the activity element should have the following attribute:


  • Thank you so much! I've been searching for this for hours. Wish they would put it in the Qt Notifier example itself!

Log in to reply