无法在 android 中获取广告 ID

not able to get advertising id in android

我正在使用下面的代码在 android 中获取广告 ID,但它给出了以下异常。

06-12 12:14:19.034: E/AndroidRuntime(13631): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.authorwjf.amianemulator/com.authorwjf.amianemulator.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.android.gms.ads.identifier.AdvertisingIdClient$Info.getId()' on a null object reference

我在 android 清单文件中添加了 google 播放服务库和元标记。

我在 activity 的 oncreate 方法中使用以下代码。

 Info adInfo = null;

    try {
         adInfo = AdvertisingIdClient.getAdvertisingIdInfo(this);
    } catch (IOException e) {

    } catch (GooglePlayServicesNotAvailableException e) {

    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (GooglePlayServicesRepairableException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String AdId = adInfo.getId();
    System.out.println("AdId :: "+AdId);

有些疑惑::

  1. genymotion支持广告id吗?

  2. 所有使用 4.0 及更高版本的 android 手机都可以使用广告 ID 吗?

请帮我获取广告ID。

您收到此异常是因为 Google Play 服务未安装在设备(或模拟器)上。

您可以在 Google Play 服务文档中看到:

Note: Because it is hard to anticipate the state of each device, you must always check for a compatible Google Play services APK before you access Google Play services features.

Reference: https://developers.google.com/android/guides/setup#ensure_devices_have_the_google_play_services_apk

您可以使用isGooglePlayServicesAvailable方法检查Google Play服务是否安装,例如:

if(GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
    //Google Play Services are available
} else {
    //Google Play Services are not available, or not updated
}

does genymotion support advertising id?

可以,但您需要手动安装 Google Play 服务。看到这个 answer.

is advertising id available in all the android phones which is using 4.0 and above?

不,Google Play 服务可能不可用。