MigrationReceiver: Add logic to do migrations on version bumps

Signed-off-by: Aayush Gupta <aayushgupta219@gmail.com>
This commit is contained in:
Aayush Gupta
2024-05-27 12:52:29 +05:30
parent cabfaa983b
commit 687a7c1540
3 changed files with 65 additions and 0 deletions

View File

@@ -159,5 +159,14 @@
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
<!-- MigrationReceiver (for running migrations) -->
<receiver
android:name=".data.receiver.MigrationReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
</application>
</manifest>

View File

@@ -0,0 +1,54 @@
package com.aurora.store.data.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.aurora.store.data.work.CleanCacheWorker
import com.aurora.store.util.Preferences
import com.aurora.store.util.Preferences.PREFERENCE_INTRO
import com.aurora.store.util.Preferences.PREFERENCE_MIGRATION_VERSION
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MigrationReceiver: BroadcastReceiver() {
private val TAG = MigrationReceiver::class.java.simpleName
private val prefVersion = 1 // BUMP THIS MANUALLY ON ADDING NEW MIGRATION STEP
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent?.action == Intent.ACTION_MY_PACKAGE_REPLACED) {
val oldVersion = Preferences.getInteger(context, PREFERENCE_MIGRATION_VERSION)
// Run required migrations on version upgrade for existing installs
if (Preferences.getBoolean(context, PREFERENCE_INTRO) && oldVersion != prefVersion) {
val newVersion = upgradeIfNeeded(context, oldVersion)
Preferences.putInteger(context, PREFERENCE_MIGRATION_VERSION, newVersion)
}
}
}
private fun upgradeIfNeeded(context: Context, oldVersion: Int): Int {
Log.i(TAG, "Upgrading from version $oldVersion to version $prefVersion")
var currentVersion = oldVersion
// Add new migrations / defaults below this point
// Always bump currentVersion at the end of migration for next release
// 58 -> 59
if (currentVersion == 0) {
CleanCacheWorker.scheduleAutomatedCacheCleanup(context)
currentVersion++
}
// Add new migrations / defaults above this point.
if (currentVersion != prefVersion) {
Log.e(TAG, "Upgrading to version $prefVersion left it at $currentVersion instead")
} else {
Log.i(TAG, "Finished running required migrations!")
}
return currentVersion
}
}

View File

@@ -60,6 +60,8 @@ object Preferences {
const val PREFERENCE_UPDATES_AUTO = "PREFERENCE_UPDATES_AUTO"
const val PREFERENCE_UPDATES_CHECK_INTERVAL = "PREFERENCE_UPDATES_CHECK_INTERVAL"
const val PREFERENCE_MIGRATION_VERSION = "PREFERENCE_MIGRATION_VERSION"
private var prefs: SharedPreferences? = null
fun getPrefs(context: Context): SharedPreferences {