我想在每次第一次更新或安装应用程序后打开我的应用程序时运行服务.如何在启动后检查App是否首次打开?
我试过这个但是onCreate方法中的代码,但我在更新我的代码时得到isFirst = true,但是它应该是空白/ null以便我可以运行我的服务.
我哪里错了?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFirst = sPrefs.getString(Utility.KEY_IS_FIRST, "");
if(isFirst == null || isFirst.equalsIgnoreCase("")){
//run service and set isFirst = true
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(Activity_Home.this);
SharedPreferences.Editor edit = preferences.edit();
edit.putString(Utility.KEY_IS_FIRST, "true");
edit.commit();
}
}
解决方法:
您可以将版本代码保存到共享首选项,并将其与当前运行的应用程序的版本代码进行比较.如果您的版本代码高于保存的版本代码,则用户已更新,运行您的服务并更新共享首选项.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int currentVersionCode = BuildConfig.VERSION_CODE;
if (prefs.getInt("LASTVERSION", 0) < currentVersionCode) {
// Run service here
prefs.edit().putInt("LASTVERSION", currentVersionCode).apply();
}
标签:android
来源: https://codeday.me/bug/20190724/1526043.html