If you’re a regular Qt user (like me) and have tried writing Android applications with Qt then you must have come across situations where you’ve needed some very simple capabilities of Android API but it wasn’t present in the Qt library. Displaying a Toast message in Qt for Android is one of those situations. In this post I’m going to describe how to display Toast messages in Qt for Android, and it’s also a very good example of showing how to use JNI (QAndroidJniObject class in Qt, along with Java code) to access Java code from within C++/Qt code.
You can skip to end of this post and view the Git repository if you wish to see the code and be done with it 🙂
First, make sure you have the following in your Qt PRO file:
android: {
QT += androidextras
ANDROID_PACKAGE_SOURCE_DIR = $$PWD / android
}
This will allow using Android specific classes of Qt, namely QAndroidJniObject and also set our Android specific source codes and other files.
Our Java code will look like this:
public class QtAndroidToastJava extends QtActivity
{
private static QtAndroidToastJava thisInstance;
public QtAndroidToastJava()
{
thisInstance = this;
}
public static void sMakeToast(String msg)
{
thisInstance.makeToast(msg);
}
private void makeToast(String msg)
{
final String tmpStr = msg;
runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(QtAndroidToastJava.this, tmpStr, Toast.LENGTH_LONG).show();
}
});
}
}
And finally we need to call the Java method responsible for displaying the Toast message from our C++/Qt code:
QAndroidJniObject tstMsg = QAndroidJniObject::fromString("Hello world! :)");
QAndroidJniObject::callStaticMethod<void>("com/amin/QtAndroidToastJava/QtAndroidToastJava",
"sMakeToast",
"(Ljava/lang/String;)V",
tstMsg.object<jstring>());
Make sure to use the Search function of this website to search for other JNI related codes and examples to better understand the way Java code is accessed from C++ in Qt.
Use the following Git repository to clone a ready to build version of the example described in this post:
https://bitbucket.org/amahta/qtandroidtoastjava/src
Post your comments and questions below if you face any issues with the code.
i have cloned your project while building or running the project i am getting error class not found exception.
Not enough info. Can you share a bit more details?
you can have the full access of the Toast Jobject from c++ using QAndroidJniObject, the class you created was not needed, just search around how create a java class’s instance from QAndroidJniObject and then call the “makeToast” and “show” methods directly then.
Thanks for pointing this out Ahmed Arif. Much appreciated. But as I said “it’s also a very good example of showing how to use JNI” so consider this an example for that please.