如何更新Android应用程序时,清除旧preferences? [英] How to clear old preferences when updating Android app?

查看:256
本文介绍了如何更新Android应用程序时,清除旧preferences?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有谷歌播放市场上的应用程序。对于我不会打扰进入种种原因,我已经改变了我的一些preferences类型。例如,一个preference类型是一个整数,并在最近的版本,它现在是一个字符串。我想这是不好的做法,但不幸的是我不得不这样做。

I have an app on the Google Play market. For various reasons that I won't bother going into, I have changed the type of some of my preferences. For example a preference type was an Integer and in the most recent version it is now a String. I imagine this isn't good practice but unfortunately I had to do it.

我担心的是,当有人更新到新版本的应用程序将崩溃为preference类型发生了变化。出于这个原因,我想清楚,每当应用程序更新时,preferences(我又意识到不理想!)

My concern is that when someone updates to the new version their app will crash as the preference types have changed. For this reason I would like to clear the preferences whenever the app is updated (again I realise not ideal!)

这可能吗?

推荐答案

共享preferences.Editor 类有一个明确() 函数,什么删除所有存储的preferences(后提交())。你可以创建一个布尔标志,将显示是否有更新的需要:

The SharedPreferences.Editor class has a clear() function, what removes all your stored preferences (after a commit()). You could create a boolean flag which will indicate if updated needed:

void updatePreferences() {
    SharedPreferences prefs = ...;
    if(prefs.getBoolean("update_required", true)) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();

        /*....make the updates....*/

        editor.putBoolean("update_required", false)
        editor.commit();
    }
}

在这之后,你需要调用这个在你的主(第一个开始)的活动,您可以访问任何preferenes之前。

And after that you need to call this in your main (first starting) activity, before you access any preferenes.

修改

要获得最新的版本(清单中所声明的版本code):

To get the current version (The versionCode declared in the manifest):

int version = 1;
try {
    version = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
    e.printStackTrace();
}

if(version > ...) {
    //do something
}

修改

如果你想要做一些更新操作,每当版本变动,那么你可以做这样的事情:

If you want to do some updating operation, whenever the version changes, then you can do something like this:

void runUpdatesIfNecessary() {
    int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    SharedPreferences prefs = ...;
    if (prefs.getInt("lastUpdate", 0) != versionCode) {
        try {
            runUpddates();

            // Commiting in the preferences, that the update was successful.
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("lastUpdate", versionCode);
            editor.commit();
        } catch(Throwable t) {
            // update failed, or cancelled
        }
    }
}

这篇关于如何更新Android应用程序时,清除旧preferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆