获取谷歌广告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);
            }
        }
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值