Skip to content

Instantly share code, notes, and snippets.

@bharath914
Last active April 17, 2024 06:39
Show Gist options
  • Save bharath914/bb0604820c7b9fd4090c9ceb8c63d48d to your computer and use it in GitHub Desktop.
Save bharath914/bb0604820c7b9fd4090c9ceb8c63d48d to your computer and use it in GitHub Desktop.
Google Play In app Review
implementation("com.google.android.play:review-ktx:2.0.1")
implementation("com.google.android.play:review:2.0.1")
// data store pref's to store the date opened time.
class DataStoreRepo @Inject constructor(
context: Context,
) {
private object PrefKeys {
val firstOpenedTime = longPreferencesKey(DataStoreCons.FIRST_OPENED_TIME)
}
private val dataStore = context.dataStorePrefs
suspend fun setFirstTimeOpenedTime(timeInMillis: Long) {
withContext(IO) {
dataStore.edit {
it[PrefKeys.firstOpenedTime] = timeInMillis
}
}
}
// returns 0 as default value.
fun getFirstTimeOpenedMillis(): Flow<Long> {
return dataStore.data.catch {
if (it is IOException) {
emit(emptyPreferences())
} else {
throw it
}
}.map {
it[PrefKeys.firstOpenedTime] ?: 0L
}
}
}
// invoking this in the viewmodel.
class MainViewModel @Inject constructor(
private val checkIfFirstLaunchTimeIsStored: CheckIfFirstLaunchTimeIsStored,
) : ViewModel() {
fun checkTheFirstLaunchTime(activity: Activity) {
viewModelScope.launch {
checkIfFirstLaunchTimeIsStored(activity)
}
}
}
// in the mainactivity or a preferred ui screen
LaunchedEffect(key1 = true) {
viewModel.checkTheFirstLaunchTime(this@MainActivity)
}
// class to check whether the user had opened the app atleast a day ago.
class CheckIfFirstLaunchTimeIsStored @Inject constructor(
private val dataStoreRepo: DataStoreRepo,
) {
suspend operator fun invoke(activity: Activity) {
val time = dataStoreRepo.getFirstTimeOpenedMillis().filterNotNull().first()
if (time == 0L) {
storeToDataStore()
} else {
val oneDayInMillis = 24L * 60L * 60L * 1000L// equals to one day in millis.
val currentTime = Calendar.getInstance().timeInMillis
val difference = currentTime - time
if (difference >= oneDayInMillis) {
// if the difference is greater than a day.
showFeedBackDialog(activity)
}
}
}
// play review api to invoke in-app review functionality.
private fun showFeedBackDialog(activity: Activity) {
val reviewManager = ReviewManagerFactory.create(activity)
reviewManager.requestReviewFlow().addOnCompleteListener { task ->
if (task.isSuccessful) {
reviewManager.launchReviewFlow(activity, task.result)
}
}
}
// if it's first launch of app then store the time in data store prefs
private suspend fun storeToDataStore() {
val calendar = Calendar.getInstance()
dataStoreRepo.setFirstTimeOpenedTime(calendar.timeInMillis)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment