How to get Google Ad Id in android Java

Viewed 1474

I am trying to get the google ad id (GAID)in android java but I am getting exeception like:

androidx.ads.identifier.AdvertisingIdNotAvailableException: No compatible AndroidX Advertising ID Provider available.

My Code

ListenableFuture<AdvertisingIdInfo> adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
    System.out.println("adinfo"+adInfo.toString());
    try {
      String id =   adInfo.get().getId();

      System.out.println("adod"+id);
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

And dependienced i added

  implementation 'com.google.android.gms:play-services-ads:19.4.0'
        implementation 'androidx.ads:ads-identifier:1.0.0-alpha04'

In Manifest I added

  <meta-data
                android:name="com.google.android.gms.ads.AD_MANAGER_APP"
                android:value="true"/>

I have tried many solutions but it is not useful. Please help me out to solve the issue.

1 Answers

The gaid dependency in androidx seems to be at fault.

Many people (including me) have followed Google's ad ID documentation and have reported the same issue. Also, Google's documentation on this matter appears outdated since the examplatory code snippet is wrong (e.g. function addCallback is missing a parameter).

The solution is to add this dependency in your gradle file instead of the ones you mentioned:

implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'

You can then fetch the advertising id this way:

            AdvertisingIdClient.Info idInfo;

            try {
                idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
                String advertisingId = idInfo.getId();

                //do sth with the id

            } catch (IOException e) {
                e.printStackTrace();

            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();

            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            }

If you want to use the id only when the user hasn't opted out of personalised ads, you can add this after retrieving the id info:

     //if user hasn't opted out of ads in device settings
     if(idInfo.isLimitAdTrackingEnabled()) {
         //do sth with the id
     }

Edit: The mentioned Google's documentation actually has a note that encourages you to use the ads identifier library I mentioned:

enter image description here

Related