Skip to content

Instantly share code, notes, and snippets.

@handstandsam
Created February 28, 2022 20:29
Show Gist options
  • Save handstandsam/686a1bb551d0426b51dd612890f64986 to your computer and use it in GitHub Desktop.
Save handstandsam/686a1bb551d0426b51dd612890f64986 to your computer and use it in GitHub Desktop.
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()
}
}
@codeBaron-dev
Copy link

Simple to use. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment