获取谷歌广告ID

1. 官方文档介绍

链接地址

2. 接口使用限制

  • 设备能翻墙,安装 Google play,并保证 Google Play 服务可用
  • 接口调用 getAdvertisingIdInfo 需要在子线程,在主线程调用会抛 IllegalStateException 异常

3. 获取示例

3.1 将谷歌服务引入到项目

  • 在顶层的 build.gradle 引用仓库
repositories {
      ...
       maven { url "https://maven.google.com" }
     ...
   }
  • 在应用层的 build.gradle 添加依赖
apply plugin: 'com.android.application'
...
dependencies {
   implementation 'com.google.android.gms:play-services-ads:19.4.0'
}

3.2 代码实例

    public class GoogleAdvertisingIdTask extends AsyncTask<Void, Void, String> {
        private Context ctx;
        private ResultCallback mCallback;

        public GoogleAdvertisingIdTask(Context context, ResultCallback callback) {
            this.ctx = context;
            this.mCallback = callback;
        }

        @Override
        protected String doInBackground(Void... voids) {
            // 获取谷歌广告ID
            AdvertisingIdClient.Info idInfo = null;
            try {
                idInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            }
            String adid = null;
            try {
                if (idInfo != null) {
                    adid = idInfo.getId();
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            return adid;
        }

        @Override
        protected void onPostExecute(String adid) {
            if (mCallback != null) {
                mCallback.onResut(adid);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/LewisWang_/article/details/109081945