AndroidRuntime :: getJNIEnv () returns NULL

I have a code snippet below in my JNI part:

JNIEnv* env = AndroidRuntime::getJNIEnv(); 

The above statement always returns NULL in my function. Then I use env and call some method in the Java code using the callback mechanism.

This piece of code in getJNIEnv () always returns NULL.

 if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { return NULL; } 

Can anyone tell me what happened to the code? This looks pretty normal to me, as other functions in JNI also have almost a similar implementation.

+4
source share
1 answer

First, do not use AndroidRuntime::getJNIEnv() . This is not part of the NDK API. Instead, you should use the JNI GetEnv function.

Secondly, GetEnv returns NULL if the current thread is not connected to the virtual machine. (Remember that JNIEnv is thread- JNIEnv .) If you created the thread yourself, you will need to use the JNI AttachCurrentThread function to attach it.

Both of them require a JavaVM pointer. There is only one of these processes, so you can get it during JNI_OnLoad or the installation call from your program ( GetJavaVM function) when you passed JNIEnv .

If you haven’t already done so, check out the JNI Tips page (which includes links to some comprehensive JNI documents).

+7
source

All Articles