I need to clear(equivalent to Clear Data in App Settings) all the old data in the app programmatically when the user updates the app from Google Play Store or any other sources. This is because I don't need any of the existing data from the old app since I have changed everything in the new app compared to the old one.
I thought of implementing a version check at the app startup, but I can't find a way to get the app's previous versionCode
or versionName
. The only way I figured out to clear the data is to check the lastUpdateTime
at the time of publishing the app. But it's not reliable since the user has other ways or sources of getting the app (like sharing it with a friend or if the user had a backup of the old app).
Any Suggestions?
You can store versionCode
in SharedPreferences
and compare with current versionCode
For clear all data you just need to clear all value of SharedPreferences, Local Database and all local files which you have store.
public void clearData()
{
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int mCurrentVersion = pInfo.versionCode;
SharedPreferences mSharedPreferences = getSharedPreferences("app_name", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.apply();
int last_version = mSharedPreferences.getInt("last_version", -1);
if(last_version != mCurrentVersion)
{
//clear all your data like database, share preference, local file
//Note : Don't delete last_version value in share preference
}
mEditor.putInt("last_version", mCurrentVersion);
mEditor.commit();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
Note : Don't delete last_version value in share preference.
You can simply use a PACKAGE_REPLACED
receiver which gets fired whenever a package is replaced in your phone (also happens when updating an app). Declare it in your manifest:
<receiver android:name=".UpdateReciever">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<data android:scheme="package" android:path="com.my.app" />
</intent-filter>
</receiver>
And add your receiver class. onReceive
will get called when the app is updated:
public class UpdateReciever extends BroadcastReceiver {
@Override
public void onReceive(Context con, Intent intent) {
}
}
EDIT: you don't need to filter the package. Use MY_PACKAGE_REPLACED
instead which will fire only for your app.
You can listen to a system broadcast with following intent and filter in onReceive with your package name to see if your app is updated.
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>