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:
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;
thisInstance = this;
public static void sMakeToast(String msg)
private void makeToast(String msg)
final String tmpStr = msg;
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! :)”);
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:
Post your comments and questions below if you face any issues with the code.