'Create toast message from android_main JNI app
I'm using the following code to spawn a toast from JNI
JNIEnv* env;
JavaVM* vm = _app->activity->vm;
jint attached = (*vm)->AttachCurrentThread(vm, &env, NULL);
if(attached < 0)
{
utils_logging_log("ERROR::FAILED TO ATTACH VM");
return 0;
}
//Toast
jclass toast = (*env)->FindClass(env, "android/widget/Toast");
if(!toast)
{
utils_logging_log("WARNING::FAILED TO Toast Class");
goto detach;
}
jmethodID methodMakeText = (*env)->GetStaticMethodID(env, toast, "makeText", "(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;");
if(!methodMakeText)
{
utils_logging_log("WARNING::FAILED TO get Toast.makeText function");
goto detach;
}
const char* msgstr = "This is a toast message";
jstring str = (*env)->NewStringUTF(env, msgstr);
jobject toastobj = (*env)->CallStaticObjectMethod(env, toast, methodMakeText,
_app->activity->clazz, str, 0);
jmethodID methodShow = (*env)->GetMethodID(env, toast, "show", "()V");
(*env)->CallVoidMethod(env, toastobj, methodShow);
//TODO : Cleanup NewStringUTF
detach:
if((*env)->ExceptionOccurred(env))
{
(*env)->ExceptionDescribe(env);
}
(*vm)->DetachCurrentThread(vm);
which results in an error from logcat
E/AndroidRuntime(10966): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
E/AndroidRuntime(10966): at android.os.Handler.<init>(Handler.java:208)
E/AndroidRuntime(10966): at android.os.Handler.<init>(Handler.java:122)
E/AndroidRuntime(10966): at android.widget.Toast$TN.<init>(Toast.java:361)
E/AndroidRuntime(10966): at android.widget.Toast.<init>(Toast.java:107)
E/AndroidRuntime(10966): at android.widget.Toast.makeText(Toast.java:272)
I have tried this for running on main thread by creating pipes and running the same code in the callback for ALooper but still get the same error
Is it possible to 'runOnUiThread' without needing Java code? Just using android_main?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
