How to get app package name or applicationId using JNI android

后端 未结 2 815
萌比男神i
萌比男神i 2020-12-29 16:37

For the protection issue of the shared library I will try to get package name using JNI but it will give errors. So, is it possible to get package name or applicationId usin

相关标签:
2条回答
  • 2020-12-29 17:08

    This works for me:

      static jstring get_package_name(
          JNIEnv *env,
          jobject jActivity
      ) {
        jclass jActivity_class = env->GetObjectClass(jActivity);
    
        jmethodID jMethod_id_pn = env->GetMethodID(
            jActivity_class,
            "getPackageName",
            "()Ljava/lang/String;");
        jstring package_name = (jstring) env->CallObjectMethod(
            jActivity,
            jMethod_id_pn);
    
        return package_name;
      }
    
    0 讨论(0)
  • 2020-12-29 17:13

    Yes, it's possible. Android is based on Linux, we can obtain a lot of information in user space provided by kernel.

    In your example, the information stored here /proc/${process_id}/cmdline

    We can read this file, and get the application id.

    See a simple example

    #include <jni.h>
    #include <unistd.h>
    #include <android/log.h>
    #include <stdio.h>
    
    #define TAG "YOURAPPTAG"
    
    extern "C"
    JNIEXPORT void JNICALL
    Java_com_x_y_MyNative_showApplicationId(JNIEnv *env, jclass type) {
    
        pid_t pid = getpid();
        __android_log_print(ANDROID_LOG_DEBUG, TAG, "process id %d\n", pid);
        char path[64] = { 0 };
        sprintf(path, "/proc/%d/cmdline", pid);
        FILE *cmdline = fopen(path, "r");
        if (cmdline) {
            char application_id[64] = { 0 };
            fread(application_id, sizeof(application_id), 1, cmdline);
            __android_log_print(ANDROID_LOG_DEBUG, TAG, "application id %s\n", application_id);
            fclose(cmdline);
        }
    }
    
    0 讨论(0)
提交回复
热议问题