简体   繁体   中英

How to get app package name or applicationId using JNI android

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 using JNI? If anyone have example or references for this problem then suggests. Because not any good tutorial or solution available. Else any other way suggest of the protection of the shared library.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM