I am trying display a toast on the Java method call from C++ side I have managed to call that method and even getting string but Toast is not working I have tried almost everything with context and all
C++ Side
JavaVMAttachArgs args = { JNI_VERSION_1_6, NULL, NULL };
vm->AttachCurrentThread( &env, &args );
activityConstructor = env->GetMethodID(activity, "<init>", "()V");
jobject object = env->NewObject(activity, activityConstructor);
toastID = env->GetMethodID(activity, "toast", "(Ljava/lang/String;)V");
qDebug() << "Moving";
jstring message1 = env->NewStringUTF("This comes from jni.");
qDebug()<< "Test" << message1;
env->CallVoidMethod(object, toastID, message1);
Java Side
public void toast(String message){
messageData = message;
Log.d(TAG, message);
new Thread()
{
public void run()
{
esActivity.this.runOnUiThread(new Runnable(){
public void run(){
Log.d("Message in UIThread", messageData);
Toast.makeText(context, messageData, Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
I am gettin string value in message but this Toast does not show anything
Any idea would be appreciated ..thanks
After analyzing my code deeply, I figured out the issue in my code. Hopefully this answer would be helpful for someone in future.
It was the issue in the JNI call in C++ for java method. I had to call the DetachCurrentThread()
as in JNI the native thread remains attached to VM and it stays inside native method. Improved correct code is
JavaVMAttachArgs args = { JNI_VERSION_1_6, NULL, NULL };
vm->AttachCurrentThread( &env, &args );
activityConstructor = env->GetMethodID(activity, "<init>", "()V");
jobject object = env->NewObject(activity, activityConstructor);
toastID = env->GetMethodID(activity, "toast", "(Ljava/lang/String;)V");
qDebug() << "Moving";
jstring message1 = env->NewStringUTF("This comes from jni.");
qDebug()<< "Test" << message1;
env->CallVoidMethod(object, toastID, message1);
vm->DetachCurrentThread();