Android: automatically attach to the JVM non-SDL threads
authorSylvain Becker <sylvain.becker@gmail.com>
Sun, 20 Jan 2019 22:11:56 +0100
changeset 12563db549862a09a
parent 12562 d21956a01eed
child 12564 04ec6bb43c4e
Android: automatically attach to the JVM non-SDL threads

It allows a thread created with pthread_create() to access the JNI Env
src/core/android/SDL_android.c
     1.1 --- a/src/core/android/SDL_android.c	Sun Jan 20 12:02:12 2019 -0800
     1.2 +++ b/src/core/android/SDL_android.c	Sun Jan 20 22:11:56 2019 +0100
     1.3 @@ -331,7 +331,27 @@
     1.4      /* Get JNIEnv from the Thread local storage */
     1.5      JNIEnv *env = pthread_getspecific(mThreadKey);
     1.6      if (env == NULL) {
     1.7 -        __android_log_print(ANDROID_LOG_ERROR, "SDL", "JNIEnv is NULL. Call Android_JNI_SetupThread() first.");
     1.8 +        /* If it fails, try to attach ! (e.g the thread isn't * created with SDL_CreateThread() */
     1.9 +        int status;
    1.10 +
    1.11 +        /* There should be a JVM */
    1.12 +        if (mJavaVM == NULL) {
    1.13 +            __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed, there is no JavaVM");
    1.14 +            return 0;
    1.15 +        }
    1.16 +
    1.17 +        /* Attach the current thread to the JVM and get a JNIEnv.
    1.18 +         * It will be detached by pthread_create destructor 'Android_JNI_ThreadDestroyed' */
    1.19 +        status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
    1.20 +        if (status < 0) {
    1.21 +            __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to attach current thread (err=%d)", status);
    1.22 +            return NULL;
    1.23 +        }
    1.24 +
    1.25 +        /* Save JNIEnv into the Thread local storage */
    1.26 +        if (Android_JNI_SetEnv(env) < 0) {
    1.27 +            return NULL;
    1.28 +        }
    1.29      }
    1.30  
    1.31      return env;