Nowadays we are using Google advertising id as a unique identifier besides IMEI, GSM subscriber id, Device id, etc. Let’s have a look at how we can retrieve or fetch google ads/advertisement id using Kotlin coroutines.
import android.content.Context
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class AdsInfo(val context: Context) {
private val adInfo = AdvertisingIdClient(context.applicationContext)
//Connect with start(), disconnect with finish()
suspend fun getAdvertisingId(): String =
withContext(Dispatchers.IO) {
adInfo.start()
val adIdInfo = adInfo.info
adInfo.finish()
adIdInfo.id
}
}
var adsId: String?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
runBlocking {
adsId = AdsInfo(context).getAdvertisingId()
}
}