Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AndroidRuntime::getJNIEnv() returns NULL

Tags:

android

I have the below code snippet in my the JNI part:

JNIEnv* env = AndroidRuntime::getJNIEnv();

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

It's this part of the code in getJNIEnv() that always returns NULL.

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

Can anyone please tell me what's wrong with code? It looks pretty normal to me since other functions in JNI too have almost similar implementation.

like image 207
webgenius Avatar asked Feb 25 '23 16:02

webgenius


1 Answers

First, don't use AndroidRuntime::getJNIEnv(). That's not part of the NDK API. You should be using the JNI GetEnv function instead.

Second, GetEnv returns NULL if the current thread is not attached to the VM. (Remember, JNIEnv is thread-specific.) If you created the thread yourself, you will need to use the JNI AttachCurrentThread function to attach it.

Both of these require a JavaVM pointer. There's only one of these per process, so you can get it during JNI_OnLoad or a setup call from your program (GetJavaVM function) when you have a JNIEnv passed in.

If you haven't yet, read through the JNI Tips page (which includes references to some comprehensive JNI docs).

like image 177
fadden Avatar answered Mar 07 '23 14:03

fadden