Advertising IDの取得

毎回忘れるので取得の仕方をメモしておく。

仕様・実装方法

仕様や実装については以下を見ておけば恐らくOK。

Advertising ID | Android Developers

AdvertisingIdClientのリファレンスは以下を参照。

https://developers.google.com/android/reference/com/google/android/gms/ads/identifier/AdvertisingIdClient

実装

Advertising IDを取得するには、プロジェクトにplay-services-adsを追加する必要がある。appモジュールレベルのbuild.gradleのdependenciesに以下を追加。

implementation "com.google.android.gms:play-services-ads:$play_services_version"

getAdvertisingIdInfoはUI Threadで取得するとIllegalStateExceptionを吐くため、別Threadで実行する必要がある。AsyncTaskがツライのでKotlinのcoroutineを使うとスッキリと書ける。

// 別Threadで実行
launch {
    // Advertising IDを取得
    val id = try {
        AdvertisingIdClient.getAdvertisingIdInfo(context).id
    } catch (e: Exception) {
        null
    }
}