NDK onDestroy cleanup app - how to disable CurrentThread

So, if we attach, we have to disconnect the stream after it finishes, right?

JNIEnv* get_jni_env() { JNIEnv* res; JAVA_VM->GetEnv((void**) &res, JNI_VERSION_1_6);//Using cached JavaVM JAVA_VM->AttachCurrentThread(&res, NULL); return res; } 

I call the following native method from @Override protected void onDestroy () of my Activity class

  void free_jni_manager() { JNIEnv* env = get_jni_env(); ... //Here i delete global refs (jclass) //JAVA_VM->DetachCurrentThread(); } 

ERROR: disconnecting stream with interpolation frames (count = 16) - the main stream is still working, and we are trying to disconnect it.

Even if we take any function using JNIEnv (for example, calling java methods), setting DetachCurrentThread will result in the same error.

DetachCurrentThread works flawlessly if used in the pthread function

 static void* thread_func(void* arg) { get_jni_env(); // attach new thread //Do thread stuff JAVA_VM->DetachCurrentThread();//thread done detached it with ok return NULL; } 

Do we need to disconnect the main thread, and we did it with JNI, yes? Or then the activity will be destroyed, it will be freed from JavaVM? Do we need to call DestroyJavaVM () (just crash when using onDestroy), how to handle this free JavaVM caching or garbage cleaner?

PS What are the benefits of using AttachCurrentThreadAsDaemon ()

+3
source share
2 answers

The Activity.onDestroy() method is called on the user interface thread. Why are you trying to separate the Java virtual machine from the user interface thread? This thread is managed by the system, you should not attach or detach the Java virtual machine from it.

JNIEnv* is available for each native method as the first parameter. Why do you need get_jni_env() in the first place?

If you need JNIEnv in worker threads, you need to attach and detach (OR create a thread from Java, it's pretty simple).

EDIT: If this is a re-attachment, you do not need to disconnect. This is not a counted system. AttachCurrentThread documented as

Attempting to attach a thread that is already attached does not work.

Unlike the required coordinated connections / disconnections.

+3
source

Do not call the JNI handler function from the main thread . Calling the JNI handler function from the main thread will crash.

+1
source

Source: https://habr.com/ru/post/1441517/


All Articles