SharedPreferences 在 Android 中最后 open/close 次未返回

SharedPreferences not returning last open/close time in Android

我正在尝试检查该应用程序是否在过去一小时内打开过。我正在使用 SharedPreferences class 来执行此操作。然而,虽然我只在几分钟内 运行 应用程序,但当我检查我的当前时间和上次 运行 时间时,时差大约 5 小时。

我在 Android Studio 上这样做。我不确定关闭模拟器和 运行 应用程序再次打开模拟器是否会影响这个。

我在调试模式下尝试 运行ning,但它从来没有在不到一个小时的时间内命中。

public class MainWindowActivity extends AppCompatActivity {
    public boolean runLastHour = false;

    SharedPreferences pref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_window);

        pref = PreferenceManager.getDefaultSharedPreferences(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_window, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        long lastRun = pref.getLong("LAST_RUN", -1);
        if (lastRun == -1){
            //first run after install
        } else {
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastRun <= (1000 * 60 * 60)) {// less than 1 hour
                runLastHour = true;
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        pref.edit().putLong("LAST_RUN", System.currentTimeMillis()).apply();
    }
}

您首先调用了 super class 的 onStop 方法,然后尝试在 SharedPreference 中提交您的值。相反,您应该首先提交值,然后调用 super class 的 onStop() 方法。

试试这个方法,

@Override
protected void onStop() {
    pref.edit().putLong("LAST_RUN", System.currentTimeMillis()).apply();
    super.onStop();
}

在调用超级 class 的方法之前调用 commit() 或 apply() 方法。