2

我试图通过 JNI 从pthreadC++ 类中创建的回调。使用以下代码。我可以从我的 Android 应用程序触发按钮按下并且我的callbackStringJNI()工作正常。的创建pthread是由通过 JNI 传递的按钮按下触发的。如果由pthread尝试异步调用创建的函数/线程callbackStringJNI(),我会在 Android 应用程序中获得传递的字符串messageMe()(仅在调试器中断时查看),但如果我尝试使用字符串(IE,在 UI 上显示某些内容),应用程序在 Android 源“Handler.class”函数上中断joinThreadPool,然后如果我再次恢复,我会在下面的 Android 代码中点击“异常”:

Android API 错误代码:

public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might    occur: " +
                klass.getCanonicalName());
        }
    }

    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(//////////Hits here - this message is never actually displayed though.
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

我可以将字符串复制到另一个变量,如 中所示messageMe(),但我仍然不能使用 aToast甚至 a中的字符串TextView。我现在很困惑为什么我不能从 a 回调pthread,欢迎提出任何建议。

安卓Java:

 package com.example.somecontrol1;

public class MainActivity extends Activity {

// load the library - name matches jni/Android.mk
static {
    System.loadLibrary("ndkfoo");
    }

    private native String inintNativeClass();
    private native String SetUpSocketNC();
    private native void initJNICallback();

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    initJNICallback();
    inintNativeClass();  


  public void messageMe(String text) {             
    String teststr = text;
    Toast.makeText(getApplicationContext(), teststr, Toast.LENGTH_LONG).show();
    //appendTextAndScroll(text, gtv);
  } 

}

在下面的代码中,当getJNIEnv()被调用并且执行来自按钮按下时,JNI_OK就是结果。当调用来自 pthread 中的回调时,JNI_EDETACHED是结果并AttachCurrentThread()成功。

JNI C ndkfoo.c

#include <jni.h>   
#include "testSocketClassWrapper.hpp"

static JavaVM* cachedJVM;
static jobject g_javaObj;
static jclass cachedclassID;
void *m_GBLpmyCSocket = NULL;


 jint JNI_OnLoad(JavaVM *jvm, void *reserved)
 {
  cachedJVM = jvm;

  JNIEnv* env;
  if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_4) != JNI_OK) {
    LOGD("GETENVFAILEDONLOAD");
    return -1;
  }
  return JNI_VERSION_1_4;
 }   

void Java_com_example_somecontrol1_MainActivity_initJNICallback(JNIEnv* env, jobject jobj) {
     //LOGD("Java_org_test_games_Wrapper_initJNIBridge()");

        g_javaObj = (*env)->NewGlobalRef(env, jobj);


        jclass storeclassID = (*env)->FindClass(env, "com/example/somecontrol1/MainActivity");
        if ( (*env)->ExceptionCheck(env) == JNI_TRUE ){
            (*env)->ExceptionDescribe(env);
              LOGD("got into exception describe");
        }
        cachedclassID = (jclass)(*env)->NewGlobalRef(env, storeclassID);
        if ( (*env)->ExceptionCheck(env) == JNI_TRUE ){
                (*env)->ExceptionDescribe(env);
                  LOGD("got into exception describe");
        }
}

jstring Java_com_example_somecontrol1_MainActivity_inintNativeClass(JNIEnv * env, jobject object){
    m_GBLpmyCSocket = (void *)MyClass_create();
return (*env)->NewStringUTF(env, "launched class");
}

typedef struct JniMethodInfo_
{
    JNIEnv*    env;
    jclass      classID;
    jmethodID   methodID;
} JniMethodInfo;

static JNIEnv* getJNIEnv()//was JNIEnv
{
//JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
if (NULL == cachedJVM) {
    LOGD("Failed to get JNIEnv. JniHelper::getJavaVM() is NULL");
    return NULL;
}

JNIEnv *env = NULL;
// get jni environment
jint ret = (*cachedJVM)->GetEnv(cachedJVM, (void**)&env, JNI_VERSION_1_4);

switch (ret) {
    case JNI_OK :
        // Success!
        LOGD("getenv successA");
        return env;

    case JNI_EDETACHED :
        // Thread not attached
        LOGD("thread not attached");
        // TODO : If calling AttachCurrentThread() on a native thread
        // must call DetachCurrentThread() in future.
        // see: http://developer.android.com/guide/practices/design/jni.html

        if ((*cachedJVM)->AttachCurrentThread(cachedJVM, &env, NULL) < 0)
        {
            LOGD("Failed to get the environment using AttachCurrentThread()");
            return NULL;
        } else {
            // Success : Attached and obtained JNIEnv!
            LOGD("getenv successB");
            return env;
        }

    case JNI_EVERSION :
        // Cannot recover from this error
        LOGD("JNI interface version 1.4 not supported");
    default :
        LOGD("Failed to get the environment using GetEnv()");
        return NULL;
    }
}    

static bool getMethodInfo(JniMethodInfo *methodinfo, const char *methodName, const char *paramCode)
{
jmethodID methodID = 0;
JNIEnv *pEnv = 0;
bool bRet = false;

do
{
    pEnv = getJNIEnv();
    if (! pEnv)
    {
        LOGD("getJNIEnv Break Called");
        break;
    }

    //jclass classID = getClassID(pEnv);
    //jclass classID = cachedclassID;

    //methodID = (*pEnv)->GetMethodID(pEnv, classID, methodName, paramCode);
    methodID = (*pEnv)->GetMethodID(pEnv, cachedclassID, methodName, paramCode);
    if (! methodID)
    {
        LOGD("Failed to find method id of %s", methodName);
        break;
    }

    //methodinfo->classID = classID;
    methodinfo->env = pEnv;
    methodinfo->methodID = methodID;


    bRet = true;
} while (0);

return bRet;
}

void callbackStringJNI(const char *newstr)
{
    LOGD("callbackStringJNI");    


    JniMethodInfo methodInfo;
    if (! getMethodInfo(&methodInfo, "messageMe", "(Ljava/lang/String;)V"))
    {
        LOGD("Cannot find method!");
        return;
    }

    jstring jstr = (*methodInfo.env)->NewStringUTF(methodInfo.env, newstr);    
    (*methodInfo.env)->CallVoidMethod(methodInfo.env, g_javaObj, methodInfo.methodID, jstr);
}

类包装器

//file testSocketClassWrapper.cpp
#include "testSocketClassWrapper.hpp"
#include "testSocketClass.hpp"


extern "C" void* MyClass_create() {
   return new mYNewClass;
}
extern "C" void MyClass_release(void* myclass) {
   delete static_cast<mYNewClass*>(myclass);
}
extern "C" void MyClass_sendCommandToSerialDevice(void* myclass, int cmd, int params, int id) {
   static_cast<mYNewClass*>(myclass)->sendCommandToSerialDevice(cmd,params,id);
}
extern "C" void SetUpSocket(void* myclass, int cmd, int params, int id) {
   static_cast<mYNewClass*>(myclass)->SetUpSocket(cmd,params,id);
}
extern "C" void Startcntl(void* myclass, int cmd, int params, int id) {
   static_cast<mYNewClass*>(myclass)->Startcntl();
}
extern "C" void Stopcntl(void* myclass, int cmd, int params, int id) {
   static_cast<mYNewClass*>(myclass)->Stopcntl();
}

C++ 类

//file testSocketClass.cpp
void mYNewClass::SetUpSocket(int Command, int Parameters, int DeviceID){
    thread1 = 0;
    iret1 = 0;

    iret1 = pthread_create( &thread1, NULL, &mYNewClass::thread_helper, this);
}
void mYNewClass::Startcntl(){

    callbackStringJNI("sent start");//////this works.
}

C++ 头文件

//file testSocketClass.hpp
extern "C" {
    void callbackStringJNI(const char *);
}

class mYNewClass{

public:

void *threadfunc(void)
    {    
    LOGD("in thread");
     while(1){
        LOGD("thread looping");
        callbackStringJNI("readata start");

        LOGD("sleep");
        sleep(30);
        }
    LOGD("after callbackStringJNI");////this does not work
        return(0);
    }

static void *thread_helper(void *context)
    {
        return ((mYNewClass *)context)->threadfunc();
    }
4

1 回答 1

1

找到解决方案,了解根本原因将不胜感激。

显然回调正在使用 Android 工作线程,并且无法访问 UI 线程。

修复 Android java 类功能messageMe

public void messageMe(final String text) {
   runOnUiThread(new Runnable() {
        public void run()
        {
          Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
        }
    });
}

我确实进行了另一项更改,以减少开销。initJNICallback我像这样缓存了methodID 。

static jmethodID cachedmethodID;

initJNICallback(){

    cachedmethodID  = (*env)->GetMethodID(env, storeclassID, "messageMe", "(Ljava/lang/String;)V");//no NewGlobalRef needed.
}
于 2013-11-08T22:37:53.747 回答