我的应用程序在首次运行时将文件从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();
}
}
答案 0 :(得分:20)
在我的应用中,我在共享偏好设置中保存了应用的版本代码。在每次启动时,我都会检查保存的版本代码是否低于我当前的版本代码。如果是,我会显示“什么是新的”对话框。
给这个代码一个旋转 - 我在我的主要活动的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是一个私有的SharedPreferences对象。如果它真的是第一次运行,并且用于升级,则可以使用。在首次运行代码的最后,editor.putLong使用您应用的当前版本代码更新您的共享首选项,以便下次运行不会触发您的首次运行代码。
这也得益于您的版本代码必须增加以使应用程序被市场视为升级,因此您无需记住更改单独的值以检测首次运行。
答案 1 :(得分:3)
您可以使用版本号模仿数据库端的操作。不要只有一个firstRun
变量,而是拥有firstRun
和versionNumber
,并在应用中添加静态版本号字段,并在每个版本中递增。这样,您就可以检查应用程序是否已更新,并对每次更新进行操作。
答案 2 :(得分:1)
我为此创建了类;在https://gist.github.com/2509913
下载使用示例:
long versionInstalled = App.getVersionInstalled(this);
long current_v = App.getVersion(this);
if( versionInstalled != current_v ){
Log.w("TAG", "Veresion not valid");
}
答案 3 :(得分:1)
在MainActivity的OnCreate
中运行此功能public void onUpdateFirstRun () {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
PackageInfo pInfo;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
Log.d("VersionCode", pInfo.versionCode + " ");
if (prefs.getLong(LAST_RUN_VERSION_CODE_KEY, 0) < pInfo.versionCode) {
if (!isInitializedInSP(KEY)) {
editor.putString(KEY, "");
}
//Finalize and Save
editor.putLong(LAST_RUN_VERSION_CODE_KEY, pInfo.versionCode);
editor.apply();
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
使用方法检查您是否已在先前版本中初始化它
public static boolean isInitializedInSP (String key) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContex());
Object o = mPrefs.getAll().get(key);
if (o != null) {
return true;
}
else {
return false;
}
}