如何检查是否必须在应用程序中执行更新代码?

时间:2013-10-09 07:28:54

标签: android

我有以下问题:

我在商店中有一个应用,version code 1现在我正在处理此应用的更新。 问题是,如果用户已经保存了数据,我必须在用户在更新到version code 2后第一次运行应用程序时更新数据。

我的问题是,如何在android中实现这个?这可能吗?

伪代码应如下所示:

protected void onCreate(Bundle savedInstanceState) {
    if (old_version == 1 && version_now == 2)
    {
        // my update code which will only performed once in a lifetime of the app
    }
    // ...
}

2 个答案:

答案 0 :(得分:0)

阅读应用版本,运行代码并存储在SharedPreferences中,您已经运行了代码。在这些问题中描述得非常好:

应用版本/名称:How to get the build/version number of your Android application?

仅运行一次:Run code only once after an application is installed on Android device

答案 1 :(得分:0)

如果您使用SQLiteOpenHelper来管理您的查询,则有一种名为OnUpgrade的方法会在用户升级其应用时被调用,并且该应用的新版本具有版本代码比以前更大。

使用示例:

public static void onUpgrade(SQLiteDatabase database, int oldVersion,
  int newVersion) {
    Log.w(TodoTable.class.getName(), "Upgrading database from version "
    + oldVersion + " to " + newVersion
    + ", which will destroy all old data");
    database.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
    onCreate(database);
}

如果您不想丢弃表,可以使用oldVersion和newVersion对数据库进行增量更新。您必须确保增加数据库版本号。数据库版本号作为构造函数参数传递给SQLiteOpenHelper。

增量升级的一个例子:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {                     
        if (newVersion > oldVersion) {
            db.beginTransaction();

            boolean success = true;
            for (int i = oldVersion ; i < newVersion ; ++i) {
                int nextVersion = i + 1;
                switch (nextVersion) {
                case 2:
                    success = upgradeToVersion2(db);
                    break;

                    // etc. for later versions.
                case 3:
                    success = upgradeToVersion3(db);
                    break;
                }


                if (!success) {
                    break;
                }
            }

            if (success) {
                db.setTransactionSuccessful();
            }
            db.endTransaction();
        }

    }