本文介绍了通过从Qt中的c ++ JNI发送字符串在Android中显示Toast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从C ++端在Java方法调用上显示祝酒词我设法调用了该方法,甚至获取了字符串,但是Toast无法正常工作,我已经尝试了几乎所有具有上下文和所有功能的

I am trying display a toast on the Java method call from C++ sideI 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 ++方面

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

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();

}

我是消息中的gettin字符串值,但此Toast不显示任何内容

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.

这是C ++ for Java方法的JNI调用中的问题.我必须调用DetachCurrentThread(),因为在JNI中,本机线程仍然连接到VM,并且仍在本机方法内.改进的正确代码是

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();

这篇关于通过从Qt中的c ++ JNI发送字符串在Android中显示Toast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:23