androidgoogle-playupdatesclear-cache

Android: How to Clear data on app update from Playstore


When I release an update for my app in Playstore, mostly it doesn't require clear Data/cache. But sometimes we want it to clear data on Update.

Is there a way, maybe a flag to enable, to automatically clear my App Data or Cache for a specific Update?

Or will I need to hanlde it myself through shared preferences?


Solution

  • Well we have to handle it internally. Here is how I am handling it.

    For any version if it is required to clear data, I create a field with app versionCode to clear data for in gradle file:

    defaultConfig {
            minSdkVersion 24
            targetSdkVersion 33
            buildConfigField("int", "CLEAR_DATA_VER", "123")
        }
    

    In my first Activity, I check if data is cleared for the version or not:

        ...
    
        val dataClearedVersion = Constants.dataClearedVersion(context)
    
        if (dataClearedVersion == null || dataClearedVersion < BuildConfig.CLEAR_DATA_VER ){
           Constants.cleanSharedPreferences(context)
           Constants.setDataClearedVersion(context)
         }
    ...
    
     fun dataClearedVersion(context: Context): Int? {
            val sharedPref = context.applicationContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE)
            val version = sharedPref.getInt(APP_DATA_CLEARED_K, -1)
    
            return if (version == -1) null else version
        }
    
    
    fun setDataClearedVersion(context: Context) {
        val sharedPref = context.applicationContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE).edit()
        sharedPref.putInt(APP_DATA_CLEARED_K, BuildConfig.CLEAR_DATA_VER).apply()
    }