問題描述
我如何知道哪個應用程序版本正在被 android 替換? (How do I know which app version is being replaced with android?)
I have an update that I want to run for my app based on what the previous version of the app is.
For example, if the user has version 1-5 and they are upgrading to 6 or 7 I want to run the update. Also, I don't want to run the update if they are upgrading from 6 to 7.
I've tried to accomplish this using a broadcast receiver that accepts the PACKAGE_REMOVE and PACKAGE_REPLACE intents but they don't seem to give me the information about the app that is being removed. I don't get the PACKAGE_REMOVED intent unless I'm reinstalling the same version. It's hard to tell because the debugger and the log print don't seem to catch before the intents are received. Any ideas?
@Override
public void onReceive(Context context, Intent intent) {
if (isOccurUpdated) {
return;
}
if (action.equalsIgnoreCase("android.intent.action.PACKAGE_REPLACED")) {
String name = info.versionName;
// We are assuming that we didn't get down here if we have already
// done this update
Log.d(TAG,"We receive the REPLACE intent "+name);
if (name.contains(OCCUR_ID_UPDATE) || name.contains(OCCUR_ID_UPDATE_FIX)) {
dbh.occurIdUpdate();
}
} else if (action.equalsIgnoreCase("android.intent.action.PACKAGE_REMOVED")) {
String name = info.versionName;
if (name.contains(OCCUR_ID_UPDATE)) {
isOccurUpdated = true;
}
}
}
參考解法
方法 1:
You need to store previous-version information yourself somewhere, such as:
Step #1: Create a custom Application
class, and define it in your manifest (android:name
attribute of <application>
).
Step #2: In onCreate()
of your custom Application
class, read in some persistent data structure that contains the version number of your app the last time onCreate()
ran. For example, you could have a lastVersion
value in your SharedPreferences
.
Step #3: If you see that the last version is older than your current version, do whatever upgrade logic you want.
Step #4: Write your current version out to that persistent data structure (e.g., update the SharedPreferences
).
If this is more tied to database logic, SQLiteOpenHelper
handles all of this for you.
(by DroidT、CommonsWare)