美文网首页
通过Activity线程获取Application/Contex

通过Activity线程获取Application/Contex

作者: CentForever | 来源:发表于2021-01-13 11:42 被阅读0次
#include <jni.h>
#include <string>
jobject getApplication(JNIEnv *env) {
    jobject application = NULL;
    jclass activity_thread_clz = env->FindClass("android/app/ActivityThread");
    if (activity_thread_clz != NULL) {
        jmethodID currentApplication = env->GetStaticMethodID(
                activity_thread_clz, "currentApplication", "()Landroid/app/Application;");
        if (currentApplication != NULL) {
            application = env->CallStaticObjectMethod(activity_thread_clz, currentApplication);
        } else {
            printf("Cannot find method: currentApplication() in ActivityThread.");
        }
        env->DeleteLocalRef(activity_thread_clz);
    } else {
        printf("Cannot find class: android.app.ActivityThread");
    }
    return application;
}

jobject getGlobalContext(JNIEnv *env)
{
    //获取Activity Thread的实例对象
    jclass activityThread = env->FindClass("android/app/ActivityThread");
    jmethodID currentActivityThread = env->GetStaticMethodID(activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;");
    jobject at = env->CallStaticObjectMethod(activityThread, currentActivityThread);
    //获取Application,也就是全局的Context
    jmethodID getApplication = env->GetMethodID(activityThread, "getApplication", "()Landroid/app/Application;");
    jobject context = env->CallObjectMethod(at, getApplication);
    return context;
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_mgg_threadtest_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    getApplication(env);
    std::string hello = "Hello from C++";
    if (getApplication(env)) {
        hello = "Hello World";
    }
    return env->NewStringUTF(hello.c_str());
}

jobject application = getApplication(env);

@SuppressLint("PrivateApi", "DiscouragedPrivateApi")
    private fun getApplicationInner(): Application? {
        return try {
            val activityThread = Class.forName("android.app.ActivityThread")
            val currentApplication = activityThread.getDeclaredMethod("currentApplication")
            val currentActivityThread = activityThread.getDeclaredMethod("currentActivityThread")
            val current = currentActivityThread.invoke(null as Any?)
            val app = currentApplication.invoke(current)
            app as Application
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

相关文章

网友评论

      本文标题:通过Activity线程获取Application/Contex

      本文链接:https://www.haomeiwen.com/subject/jpqmaktx.html