Fetch Google Advertising Id Android, Kotlin coroutines

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()
        }
}

chevron_left
chevron_right
5 1 vote
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x