std::string getAndroidId(JNIEnv* env) {
// get contentResolver
jobject instance = getGlobalContext(env);
if (NULL == instance) {
return "";
}
jclass activity = env->GetObjectClass(instance);
jmethodID method = env->GetMethodID(activity, "getContentResolver",
"()Landroid/content/ContentResolver;");
jobject resolverInstance = env->CallObjectMethod(instance, method);
// get android_id from android Settings$Secure
jclass androidSettingsClass =
env->FindClass("android/provider/Settings$Secure");
jmethodID methodId =
env->GetStaticMethodID(androidSettingsClass, "getString",
"(Landroid/content/ContentResolver;Ljava/lang/"
"String;)Ljava/lang/String;");
jstring param_android_id = env->NewStringUTF("android_id");
jstring android_id = (jstring)env->CallStaticObjectMethod(
androidSettingsClass, methodId, resolverInstance, param_android_id);
return static_cast<std::string>(
env->GetStringUTFChars(android_id, JNI_FALSE));
}
jobject getGlobalContext(JNIEnv* env) {
// Get the instance object of Activity Thread
jclass activityThread = env->FindClass("android/app/ActivityThread");
jmethodID currentActivityThread =
env->GetStaticMethodID(activityThread, "currentActivityThread",
"()Landroid/app/ActivityThread;");
if (0 == currentActivityThread) {
return NULL;
}
jobject at =
env->CallStaticObjectMethod(activityThread, currentActivityThread);
// Get Application, which is the global Context
jmethodID getApplication = env->GetMethodID(activityThread, "getApplication",
"()Landroid/app/Application;");
if (0 == getApplication) {
return NULL;
}
jobject context = env->CallObjectMethod(at, getApplication);
return context;
}
JNI获取AndroidID
最新推荐文章于 2024-08-22 16:16:43 发布