not able to get advertising id in android

17.5k views Asked by At

I am using below code to get advertising id in android, but its giving following exception.

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

I have added google play service library and meta tag in android manifest file.

I am using below code in activity's oncreate method.

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

Some doubts ::

  1. does genymotion support advertising id?

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

Please help me to get the advertising id.

1

There are 1 answers

3
Mattia Maestrini On BEST ANSWER

You receive this exception because the Google Play Services are not installed on the device (or emulator).

As you can read in the Google Play Services documentation:

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

You can check if the Google Play services are installed with isGooglePlayServicesAvailable method, for example:

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?

Yes, but you need to install the Google Play Service manually. See this answer.

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

No, Google Play Services could be not available.