Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Install Referrer KTX - Kotlin Coroutine friendly wrapper for the Google Play's InstallReferrerClient API. This API is used to ask Google Play about where the installation originated.
import android.content.Context
import android.os.RemoteException
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.android.installreferrer.api.ReferrerDetails
import kotlinx.coroutines.CompletableDeferred
/**
* https://developer.android.com/google/play/installreferrer/library
*
* implementation "com.android.installreferrer:installreferrer:2.2"
*/
object InstallReferrerExt {
/**
* Wraps callbacks to provide a nice Kotlin coroutine friendly interface.
*/
suspend fun getReferrerDetails(context: Context): ReferrerDetails? {
val deferredReferrerDetails = CompletableDeferred<ReferrerDetails?>()
val client = InstallReferrerClient.newBuilder(context.applicationContext).build()
client.startConnection(object : InstallReferrerStateListener {
override fun onInstallReferrerSetupFinished(responseInt: Int) {
if (responseInt == InstallReferrerClient.InstallReferrerResponse.OK) {
deferredReferrerDetails.complete(
try {
client.installReferrer
} catch (e: RemoteException) {
null
}
)
} else {
deferredReferrerDetails.complete(null)
}
client.endConnection()
}
override fun onInstallReferrerServiceDisconnected() {
if (!deferredReferrerDetails.isCompleted) {
deferredReferrerDetails.complete(null)
}
}
})
return deferredReferrerDetails.await()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment