如何在android Java中获取Google广告Id

如何在android Java中获取Google广告Id,java,android,Java,Android,我试图在android java中获得谷歌广告id(GAID),但我得到了如下的误解: androidx.ads.identifier.advisingidnoavailableexception:没有兼容的androidx广告ID提供程序。 我的代码 ListenableFuture<AdvertisingIdInfo> adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()); S

我试图在android java中获得谷歌广告id(GAID),但我得到了如下的误解:

androidx.ads.identifier.advisingidnoavailableexception:没有兼容的androidx广告ID提供程序。

我的代码

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();
    }
在我添加的清单中

  implementation 'com.google.android.gms:play-services-ads:19.4.0'
        implementation 'androidx.ads:ads-identifier:1.0.0-alpha04'
  <meta-data
                android:name="com.google.android.gms.ads.AD_MANAGER_APP"
                android:value="true"/>


我尝试过许多解决方案,但都没有用。请帮我解决这个问题。

androidx中的gaid依赖似乎是错误的

很多人(包括我)都关注并报道了同样的问题。此外,由于示例代码片段错误(例如,函数addCallback缺少一个参数),谷歌关于这个问题的文档似乎已经过时

解决方案是在gradle文件中添加此依赖项,而不是您提到的依赖项:

implementation'com.google.android.gms:play services广告标识符:17.0.0'

然后,您可以通过以下方式获取广告id:

            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();
            }
如果您只想在用户未选择退出个性化广告时使用id,则可以在检索id信息后添加此项:

     //if user hasn't opted out of ads in device settings
     if(idInfo.isLimitAdTrackingEnabled()) {
         //do sth with the id
     }
编辑:提到的谷歌文档实际上有一个注释,鼓励您使用我提到的ads标识符库: