gpt4 book ai didi

java - 通过 JNI 从 pthread 回调失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:25:34 28 4
gpt4 key购买 nike

我正在尝试通过 JNI 从在 C++ 类中创建的 pthread 回调。使用以下代码。我可以从我的 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() 中所示,但我仍然不能在 Toast 甚至 中使用该字符串> TextView 。我现在很困惑为什么我不能从 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();
}

最佳答案

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

显然回调正在使用 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.
}

关于java - 通过 JNI 从 pthread 回调失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19848648/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com