java中
/**
* 开启JNI线程
* @param view
*/
public void newJniThread(View view){
initJNI();
Log.e("399","开启jni线程前,threadName:" + Thread.currentThread().getName());
newJniThread();
Log.e("399","开启jni线程后,threadName:" + Thread.currentThread().getName());
}
public native void initJNI();
public native void newJniThread();
//jni线程中调用
public static void jniCallMethod(int i){
Log.e("399","jni call " + i + " threadName:" + Thread.currentThread().getName());
}
//jni线程中调用
public void jniCallMethodAgain(int i){
Log.e("399","jni call again" + i+ " threadName:" + Thread.currentThread().getName());
}
c中
//
// Created by cool on 2017/8/16.
//
#include "com_cool_ndktest2_MainActivity.h"
#include <android/log.h>
#include <assert.h>
#include <pthread.h>
#define TAG "399"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)
# define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
JavaVM* g_jvm = NULL;
jobject g_obj = NULL;
JNIEXPORT void JNICALL native_init_jni
(JNIEnv *env, jobject jobj){
LOGE("initJNI begin");
(*env)->GetJavaVM(env,&g_jvm);
g_obj = (*env)->NewGlobalRef(env,jobj);
}
void* thread_fun(void * arg){
JNIEnv *env;
jclass jclzz;
jmethodID jmid1,jmid2;
if((*g_jvm)->AttachCurrentThread(g_jvm,&env,NULL) != JNI_OK){
LOGE("%s AttachCurrentThread error failed ",__FUNCTION__);
return NULL;
}
jclzz = (*env)->GetObjectClass(env,g_obj);
if(jclzz == NULL){
LOGE("findClass error....");
goto error;
}
jmid1 = (*env)->GetStaticMethodID(env,jclzz,"jniCallMethod","(I)V");
if(jmid1 == NULL){
LOGE("GetStaticMethodID error....");
goto error;
}
(*env)->CallStaticVoidMethod(env,jclzz,jmid1,(int)arg);
jmid2 = (*env)->GetMethodID(env,jclzz,"jniCallMethodAgain","(I)V");
if(jmid2 == NULL){
LOGE("GetMethodID error....");
goto error;
}
(*env)->CallVoidMethod(env,g_obj,jmid2,(int)arg);
error:
if ((*g_jvm) -> DetachCurrentThread(g_jvm) != JNI_OK) {
LOGE("%s DetachCurrentThread error failed ",__FUNCTION__);
}
pthread_exit(0);
}
JNIEXPORT void JNICALL native_new_jni_thread
(JNIEnv *env, jobject jobj){
LOGE("newJniThread begin");
pthread_t pt[5];
for (int i = 0; i < 5; ++i) {
pthread_create(&pt[i],NULL,&thread_fun,(void*)i);
}
}
static const JNINativeMethod gMethodsMain[] = {
{
"initJNI","()V",(void*)native_init_jni
},
{
"newJniThread","()V",(void*)native_new_jni_thread
}
};
static int registerNativesMain(JNIEnv* engv)
{
LOGE("registerNativesMain begin");
jclass clazz;
clazz = (*engv) -> FindClass(engv, "com/cool/ndktest2/MainActivity");
if (clazz == NULL) {
LOGE("clazz is null");
return JNI_FALSE;
}
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
LOGE("jni_OnLoad begin");
JNIEnv* env = NULL;
jint result = -1;
if ((*vm)->GetEnv(vm,(void**) &env, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed\n");
return -1;
}
assert(env != NULL);
registerNativesMain(env);
return JNI_VERSION_1_4;
}