如何在JNI_ONLOAD中获取上下文

发布于 2025-02-07 03:41:52 字数 1447 浏览 2 评论 0 原文

我必须在 jni_onload 中获取上下文。由于某些原因,我必须在 system.loadlibrary()中调用 toctectbasecontext(),但不是 increate()

我在 increate()中调用 system.loadlibrary(),则该代码效果很好。

// 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;
}

有解决方案吗?谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文