android - 以编程方式通过 Kotlin 获取 Android 广告 ID
问题描述
我对 android 开发相当陌生,正在尝试获取特定设备的广告 ID。我发现了一些有关如何执行此操作的堆栈溢出建议:
val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext())
val adId = adInfo?.id
在工作线程中)。但是,这一直给我“等待服务连接超时”错误。
其他人似乎建议添加以下 gradle 依赖项帮助,但不适合我:
implementation 'com.google.android.gms:play-services-ads-identifiers:17.0.0'
implementation 'com.google.android.gms:play-services-base:17.1.0'
以及拥有
apply plugin: 'com.google.gms.google-services'
正确获取广告 ID 我缺少什么?
解决方案
我用Rxjava来求救,可以用Asyntask,协程...
RxJava
fun getAdId() { Observable.fromCallable { AdvertisingIdClient.getAdvertisingIdInfo(this).id } .subscribeOn(AppScheduler().backgroundThread()) .observeOn(AppScheduler().mainThread()) .subscribe(Consumer<String> { val adId = it }, Consumer<Throwable> { // nothing }) }
在 app/build.gradle 中导入 Rxjava:
实现'io.reactivex.rxjava2:rxjava:2.1.7'
实现 'io.reactivex.rxjava2:rxandroid:2.0.1'
使用 Kotlin 的协程:
GlobalScope.launch { val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()) val adId = adInfo?.id Log.e("text", adId) }
推荐阅读
- javascript - 如何为 vue.js 应用程序实现刷新?
- reactjs - Socket IO/React 函数没有检索到正确的值
- angular - 用户创建表单 - 更新和创建 - 使用不同的输入。角 2+
- ubuntu - 某些东西阻止 lftp 连接到远程 FTP 服务器
- xamarin.forms - 本地化在 XamarinForms PCL 中的文化 fr 不起作用
- xcode - 无法附加统一的 iOS 版本
- .htaccess - laravel api路由在ssl之后不起作用
- sql - 将两个合并为一个 SSIS
- c# - c# 读取和删除用于消息传递的文件
- php - 在 PHP 中,如何将变量放入由 HTML 组成的 php 代码中?