在Android中启动/更新后,检查App是否第一次打开

时间:2016-01-13 11:55:54

标签: android

我想在第一次更新或安装应用程序后每次打开应用程序时运行服务。如何在启动后检查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();
}
}

3 个答案:

答案 0 :(得分:7)

您可以将版本代码保存到共享首选项,并将其与当前运行的应用程序的版本代码进行比较。如果您的版本代码高于保存的版本,则用户已更新,运行您的服务并更新共享首选项。

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();
}

答案 1 :(得分:1)

使用SharedPareference,但使用它来保存您的应用版本号。每当它不同时,运行您的服务。

答案 2 :(得分:0)

您可以使用布尔变量并将其存储在共享首选项中。 当您第一次打开应用程序时将其设置为true,下次检查该变量的值

相关问题