Pong

November 12th 2014, Android JNI Revisited

November 11th 2014 Android JNI Torch | | November 12th 2014 Android JNI Torch Revisited

As seen in the previous JNI example, it is not very convenient to replace the Qt main activity with an extended one and add static wrapper methods to it. There must be a more straight forward way to use Android Java code in Qt5.

The reason for replacing the main activity was to get a handle on the main activity object. Without it we cannot access the services and items the activity owns. But there is a different way to get a handle on that object. We can use the activity() method of the QtNative class, like so:

package org.openterrain.example;

import org.qtproject.qt5.android.QtNative;
import android.app.Activity;

public class Main
{
    protected Activity activity;

    public Main()
    {
        activity = QtNative.activity();
    }
}

Now we add our methods to that base class by extending it, in our example we just write a log in “doSomething()” for testing purposes:

package org.openterrain.example;

import org.openterrain.example.Main;
import android.util.Log;

public class MyJavaClass extends Main
{
    public void doSomething()
    {
        Log.d("Example", "MyJavaClass.doSomething: package=" + activity.getPackageName());
    }
}

We place the classes in the qmake directory “ANDROID_PACKAGE_SOURCE_DIR” in the subpath “src/org/openterrain/example/Main.java” resp. “MyJavaClass.java” and add them to “OTHER_FILES”. Back in C++ we create an instance of that class and start a method call:

#include <QtAndroidExtras>

QAndroidJniObject myJavaObject("org.openterrain.example.MyJavaClass");
myJavaObject.callMethod<void>("doSomething");

With the result of the following log output:

D/Example (29540): MyJavaClass.doSomething: package=org.openterrain.example

Much more straight forward :-)

Hope that helps a lot of people having the same learning curve on Qt and Android.

November 11th 2014 Android JNI Torch | | November 12th 2014 Android JNI Torch Revisited

Options: