Using JNI to show an Android notification
← Using JNI to run own Java code | ● | The Android App Life Cycle →
As an example of running own Java code, we modify the applications state by designing a class that is able to post messages to the top application bar of Android. For that purpose we define our own Java class named ‘Notifier’.
First, the notifier class needs to gain access to the main activity object. We do so by storing the activity as a member in the base class ‘Main’:
import org.qtproject.qt5.android.QtNative;
import android.app.Activity;
public class Main
{
protected Activity activity;
public Main()
{
activity = QtNative.activity();
}
}
Next we derive from the above class and create a builder object to create and show the notifications:
import org.my.example.Main;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
public class Notifier extends Main
{
private NotificationManager m_notificationManager;
private Notification.Builder m_builder;
public void notify(String s)
{
if (m_notificationManager == null)
{
m_notificationManager = (NotificationManager)activity.getSystemService(Context.NOTIFICATION_SERVICE);
m_builder = new Notification.Builder(activity);
m_builder.setSmallIcon(R.drawable.icon);
String app = activity.getPackageName();
app = app.substring(app.lastIndexOf(".")+1);
m_builder.setContentTitle(app+":");
}
m_builder.setContentText(s);
m_notificationManager.notify(1, m_builder.build());
}
public void cancel()
{
if (m_notificationManager != null)
{
m_notificationManager.cancelAll();
}
}
}
Now we create a notifier object
notifier_ = new QAndroidJniObject("org.my.example.Notifier");
and call the method notify(…) on the newly created Notifier Java object via JNI:
QString s("hi there");
QAndroidJniEnvironment env;
jstring jarg = env->NewStringUTF(s.toStdString().c_str());
notifier_->callMethod<void>("notify", "(Ljava/lang/String;)V", jarg);
env->DeleteLocalRef(jarg);
← Using JNI to run own Java code | ● | The Android App Life Cycle →