Skip to content

Instantly share code, notes, and snippets.

@kishan-vadoliya
Created October 20, 2023 09:04
Show Gist options
  • Save kishan-vadoliya/5a5d265c1e39a6aaf7dd37761615bde2 to your computer and use it in GitHub Desktop.
Save kishan-vadoliya/5a5d265c1e39a6aaf7dd37761615bde2 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()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment