How to get the context in JNI_OnLoad, when the loadLibrary() is under attachBaseContext

393 views Asked by At

I have to get the context in the JNI_OnLoad. Due to some reason, I have to call the System.loadLibrary() in the attachBaseContext() but not onCreate().

I use the code in https://stackoverflow.com/a/46871051/5093308, but the returned context is NULL. And If I call the System.loadLibrary() in the onCreate(), that code works well.

// CustomApplication.java
public class CustomApplication extends Application {
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        System.loadLibrary("hook_main");
    }

    // @Override
    // public void onCreate() {
    //     super.onCreate();
    //     System.loadLibrary("hook_main");
    // }
}

// hook_main.c
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    // ...
    jclass activityThread = (*env)->FindClass(env, "android/app/ActivityThread");
    jmethodID currentActivityThread = (*env)->GetStaticMethodID(env, activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;");
    jobject at = (*env)->CallStaticObjectMethod(env, activityThread, currentActivityThread);
    jmethodID getApplication = (*env)->GetMethodID(env, activityThread, "getApplication", "()Landroid/app/Application;");
    // at and getApplication are not NULL
    jobject context = (*env)->CallObjectMethod(env, at, getApplication); 
    // the context is NULL
    return JNI_VERSION;
}

Is there a solution? Thanks

0

There are 0 answers