gpt4 book ai didi

Android:如何在我的应用程序更新时重置 FirstRun SharedPreferences?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:34:40 26 4
gpt4 key购买 nike

我的应用程序在第一次运行时将文件从 res/raw 复制到 SD 卡。我希望它在每次后续应用程序更新时更新这些文件。我如何让它在每次应用更新时将首次运行首选项重置为 true?

相关代码如下:

/**
* get if this is the first run
*
* @return returns true, if this is the first run
*/
public boolean getFirstRun() {
return mPrefs.getBoolean("firstRun", true);
}

/**
* store the first run
*/
public void setRunned() {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}

SharedPreferences mPrefs;

/**
* setting up preferences storage
*/
public void firstRunPreferences() {
Context mContext = this.getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
}

public void setStatus(String statustext) {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putString("status", statustext);
edit.commit();
}

}

最佳答案

在我的应用程序中,我在共享首选项中保存了应用程序的版本代码。每次启动时,我都会检查保存的版本代码是否低于我当前的版本代码。如果是,我会显示一个“新增功能”对话框。

试一试这段代码 - 我在主要 Activity 的 onCreate 中使用了它:

    PackageInfo pInfo;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
if ( prefs.getLong( "lastRunVersionCode", 0) < pInfo.versionCode ) {
// TODO: Handle your first-run situation here

Editor editor = prefs.edit();
editor.putLong("lastRunVersionCode", pInfo.versionCode);
editor.commit();
}
} catch (NameNotFoundException e) {
// TODO Something pretty serious went wrong if you got here...
e.printStackTrace();
}

prefs 是私有(private)的 SharedPreferences 对象。如果它确实是第一次运行并且用于升级,则此方法有效。在首次运行代码结束时,editor.putLong 会使用应用程序的当前版本代码更新您的共享首选项,因此下一次运行不会触发您的首次运行代码。

这也得益于以下事实:您的版本代码必须增加,应用才能被市场视为升级,因此您无需记住更改单独的值来检测首次运行。

关于Android:如何在我的应用程序更新时重置 FirstRun SharedPreferences?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4726283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com