项目上刚好要在Android NDK层使用线程回调Java层方法,仅以此文做个总结。线程使用pthread创建(在此略过),线程会循环调用NofityDataCB函数:
static JavaVM* s_jVM = NULL;
static jobject s_jobj = NULL; //java object
static jmethodID s_jcallback = NULL; //方法id
static void NotifyDataCB(unsigned char flag, int x, int y, int w, int h, unsigned char* buff, mp_i64 timeStamp)
{
//LOG_DBG("[NotifyDataCB()] enter.");
JNIEnv* env;
s_jVM->AttachCurrentThread(&env, NULL); //获取当前线程的JNIEnv*
env->CallVoidMethod(s_jobj, s_jcallback, ...); //调用java层相关方法
s_jVM->DetachCurrentThread(); //释放当前线程的JNIEnv*
//LOG_DBG("[NotifyDataCB()] done.");
return;
}
此处的重点即为:
jint AttachCurrentThread(JavaVM *vm, void **p_env, void *thr_args);
Attaches the current thread to a Java VM. Returns a JNI interface pointer in the JNIEnv