JavaVM globalVM
=
nullptr;
JNIEXPORT jint JNI_OnLoad(JavaVM
*
vm, void
*
reserved){
globalVM
=
vm;
__android_log_print(
4
,
"miniboom->jni"
,
"jni->%s"
,
"JNI_OnLoad is called"
);
jint result
=
0
;
result
=
JNI_VERSION_1_6;
JNIEnv
*
env
=
nullptr;
/
/
从JVM中获取JNIEnv
if
(vm
-
>GetEnv((void
*
*
)&env, JNI_VERSION_1_6)
=
=
JNI_OK){
__android_log_print(
4
,
"miniboom->jni"
,
"jni->%s"
,
"GetEnv((void**)&env,JNI_VERSION_1_6) is JNI_OK"
);
}
/
/
创建新线程,调用threadtest
pthread_t thread;
pthread_create(&thread, nullptr, threadtest, nullptr);
pthread_join(thread, nullptr);
return
result;
}
void
*
threadtest(void
*
args){
for
(
int
i
=
0
; i<
10
;i
+
+
){
__android_log_print(
4
,
"miniboom-jni"
,
"jni->%s,%d"
,
"i am from thread"
,i);
}
JNIEnv
*
threadenv
=
nullptr;
/
/
这是在子线程中,使用AttachCurrentThread,依附到主线程中,才能够获取threadenv这个JNIEnv,否则直接使用globalVM
-
>GetEnv会报错。
if
(globalVM
-
>AttachCurrentThread(&threadenv, nullptr)
=
=
JNI_OK) {
__android_log_print(
4
,
"miniboom-jni"
,
"jni->%s,"
,
"globalVM->AttachCurrentThread(&threadenv, nullptr) == JNI_OK"
);
jstring jstring1
=
threadenv
-
>NewStringUTF(
"threadtest jstring"
);
const char
*
content
=
threadenv
-
>GetStringUTFChars(jstring1, nullptr);
__android_log_print(
4
,
"miniboom-jni"
,
"jni->%s"
,content);
threadenv
-
>ReleaseStringUTFChars(jstring1, content);
}
else
{
__android_log_print(
4
,
"miniboom-jni"
,
"jni->%s,"
,
"globalVM->AttachCurrentThread(&threadenv, nullptr) == JNI_NOT_OK"
);
}
globalVM
-
>DetachCurrentThread();
pthread_exit(
0
);
}