重新安装时重置共享首选项



重新安装应用程序时,有没有办法删除或重置共享首选项数据,而无需卸载应用程序并安装它?

我想说的是,目前,我正在开发一个使用共享首选项的应用程序,但由于我仍在开发它,因此在进行更改后,我会继续运行该应用程序并通过 Eclipse 将该应用程序上传到测试手机。目前,我无法从预期过程的一开始(第一次之后)运行该应用程序,而无需卸载旧版本,然后再次上传应用程序。

为此,在您的启动活动中 onCreate() 方法检查共享首选项文件是否存在,如果存在,请将其删除。然后根据需要创建它。您可以像这样检查首选项文件是否存在。

public boolean isFirstTime() {
        return getDatabasePath("your file name").exists();
    }

清除以下活动:

Intent intent = new Intent(this, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

清除共享首选项:

SharedPreferences pref = this.getSharedPreferences("mypref", Context.MODE_PRIVATE);
getSharedPreferences("pref", Context.MODE_PRIVATE).edit().clear().commit();

在启动活动中检查是否使用如下函数清除首选项:

    SharedPreferences prefs = this.getSharedPreferences("prefs", Context.MODE_PRIVATE);
    if (!prefs.getBoolean("FirstRun", true)) {
        // Not the first time so clear prefs
        prefs.edit().clear().commit();
    } else {
        // Set the value for future runs
        prefs.edit().putBoolean("FirstRun", false).commit();
    }

最新更新