'why JNIEnv can't find class com/google/android/gms/ads/identifier/AdvertisingIdClient?

I'm trying env->FindClass("com/google/android/gms/ads/identifier/AdvertisingIdClient") in Instrumentation.callApplicationOnCreate and it returns NULL.

I found the FAQ: Why didn't FindClass find my class? and it says:

If you call FindClass from this thread, the JavaVM will start in the "system" class loader instead of the one associated with your application, so attempts to find app-specific classes will fail.

I also tried this in Instrumentation.callActivityOnCreate but still not found it.

  jclass class_Activity = env->FindClass("android/app/Activity");
  jclass refClass_Activity = (jclass)env->NewGlobalRef(class_Activity);
  jmethodID method_getClassLoader = env->GetMethodID(refClass_Activity, "getClassLoader", "()Ljava/lang/ClassLoader;");
  jobject classLoaderObj = env->CallObjectMethod(thisAct, method_getClassLoader);

  jclass class_ClassLoader = env->FindClass("java/lang/ClassLoader");
  jclass refClass_ClassLoader = (jclass)env->NewGlobalRef(class_ClassLoader);
  jmethodID method_findClass = env->GetMethodID(refClass_ClassLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");

  jclass class_AdvertisingIdClient_Info = static_cast<jclass>(env->CallObjectMethod(classLoaderObj, method_findClass, env->NewStringUTF("com/google/android/gms/ads/identifier/AdvertisingIdClient")));
  LOGI("class_AdvertisingIdClient_Info= %p", class_AdvertisingIdClient_Info);

I don't known env->FindClass is belongs to "system" class loader or application class loader. How to find the class AdvertisingIdClient?



Solution 1:[1]

Problem was solved.

The Application ClassLoader works well for my custom Class.

Because the App was not include com/google/android/gms/ads/identifier/AdvertisingIdClient. so we can not found it. Usually we get advertisingId through Intent to request Service.

Solution 2:[2]

In your first two calls you are using JNI functions to find classes. They expect the class name's components to be separated by "/". Your last "findClass", however, is a call to a Java method in the ClassLoader object. This expects "." as a separator.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nelson
Solution 2 user2543253