How to get Advertising ID in android programmatically

前端 未结 12 1557
迷失自我
迷失自我 2020-12-08 04:18

I want to get users Advertising ID programmatically.I used the below code from the developer site.But its not working

         Info adInfo = null;
                   


        
12条回答
  •  既然无缘
    2020-12-08 04:48

    Fetch the advertising id from background thread:

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
                    String adId = adInfo != null ? adInfo.getId() : null;
                    // Use the advertising id
                } catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
                    // Error handling if needed
                }
            }
        });
    

    I added null checks to prevent any crashes. The Google example implementation code would crash with a NullPointerException if an exception occures.

提交回复
热议问题