#include <thread>
#include <jni.h> #include <string> #include <iostream> #include <stdlib.h> #include <stdio.h>
//定义全局虚拟机对象
_JavaVM *g_javaVm;
JNIEnv *g_env;
jobject g_object;
static volatile int mIndexThreadExit = 0;
JNIEXPORT void JNICALL
Java_com_sunchip_pointreadingpen_MainActivity_initilize(
JNIEnv *env,
jobject thiz) {
//出处 https://www.cnblogs.com/MMLoveMeMM/articles/3644310.html
(*env).GetJavaVM(&g_javaVm);
g_env=env;
g_object=(jobject)(env->NewGlobalRef(thiz));;
LOGE("init gray initilize");
}
JNIEXPORT void JNICALL
Java_com_sunchip_pointreadingpen_MainActivity_startReadReuslt(
JNIEnv *env,
jobject thiz) {
mIndexThreadExit = 0;
pthread_t thredId;
if(pthread_create(&thredId,NULL,native_thread_exec,NULL)!=0){
LOGE("startReadReuslt faild");
return;
}
LOGE("init gray startReadReuslt");
}
JNIEXPORT void JNICALL
Java_com_sunchip_pointreadingpen_MainActivity_stopReadReuslt(
JNIEnv *env,
jobject thiz) {
mIndexThreadExit = 1;
LOGE("init gray stopReadReuslt");
}
//线程执行的方法
static void* native_thread_exec(void *arg){
JNIEnv *env;
(*g_javaVm) . AttachCurrentThread(&env,arg);
jclass objectClass = (*env).GetObjectClass(g_object);
jmethodID methodid = (*env).GetMethodID(objectClass,"onResultCallBack","(I)V");
if(methodid==NULL){
LOGE("create callback class null");
return 0;
}
LOGE("create thread loop enter");
int count = 0;
while(!mIndexThreadExit){
//env->CallVoidMethod(objectClass,methodid,count++)
(*env).CallVoidMethod(objectClass,methodid,count++);
//(*env)->CallVoidMethod(env,objectClass,objectClass,count++);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
(*g_javaVm).DetachCurrentThread();
LOGE("create thread loop DetachCurrentThread");
}