我的应用程序在第一次运行时将文件从res/raw复制到sdcard.我希望它在每次后续应用更新时更新这些文件.如何在每次应用更新时将firstrun首选项重置为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();
}
}
Run Code Online (Sandbox Code Playgroud)
Riv*_*Kid 21
在我的应用程序中,我在共享首选项中保存了应用程序的版本代码.在每次启动时,我都会检查保存的版本代码是否低于我当前的版本代码.如果是,我会显示一个"什么是新的"对话框.
给这个代码一个旋转 - 我在我的主要活动的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();
}
Run Code Online (Sandbox Code Playgroud)
prefs是一个私有的SharedPreferences对象.如果它真的是第一次运行,并且用于升级,则可以使用.在首次运行代码结束时,editor.putLong会使用您应用的当前版本代码更新您的共享首选项,以便下次运行不会触发您的首次运行代码.
这也得益于您的版本代码必须增加以使应用程序被市场视为升级,因此您无需记住更改单独的值以检测首次运行.
您可以使用版本号来模仿数据库端所做的事情。不要只使用一个firstRun变量,而是使用两个firstRun和versionNumber,并在应用程序中放置一个静态版本号字段,该字段在每个版本中都会递增。这样,您就可以检查应用程序是否已更新,并在每次更新时执行操作。
| 归档时间: |
|
| 查看次数: |
5158 次 |
| 最近记录: |