我想以编程方式让用户获得广告ID。我使用了开发者网站上的以下代码,但无法正常工作

         Info adInfo = null;
          try {
            adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());

          } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).

          } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
          } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (GooglePlayServicesRepairableException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          final String id = adInfo.getId();
          final boolean isLAT = adInfo.isLimitAdTrackingEnabled();

如何以编程方式获取用户的广告ID?请帮我

最佳答案

我可能会迟到,但这可能会对其他人有所帮助!

    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            AdvertisingIdClient.Info idInfo = null;
            try {
                idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String advertId = null;
            try{
                advertId = idInfo.getId();
            }catch (NullPointerException e){
                e.printStackTrace();
            }

            return advertId;
        }

        @Override
        protected void onPostExecute(String advertId) {
            Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
        }

    };
    task.execute();

10-07 12:59