首页 > 解决方案 > 以编程方式通过 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 我缺少什么?

标签: androidkotlin

解决方案


我用Rxjava来求救,可以用Asyntask,协程...

  1. 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'

  2. 使用 Kotlin 的协程:

     GlobalScope.launch {
            val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext())
            val adId = adInfo?.id
            Log.e("text", adId)
        }
    

推荐阅读