简体   繁体   English

如何在两个活动中的共享首选项中存储时间

[英]How to store time in sharedpreferences across two activities

When my users play a game, I want to lock them out of it for 30 seconds. 当我的用户玩游戏时,我想将他们锁定30秒钟。 I'm trying to use SharedPreferences . 我正在尝试使用SharedPreferences I'm not well acquainted with SP and not completely sure how to use it. 我对SP不太熟悉,也不完全知道如何使用它。 So it should look like so 所以应该看起来像这样

ifGameOver(){

//lock the game for 30 seconds 
//send users to main menu until 30seconds is over

}

and then at the main menu I wish to be able to see a TextView count down as the 30 seconds go down. 然后在主菜单上,我希望能够随着30秒的下降而看到TextView的计数。 So here I would getLong or something(?). 所以在这里我会得到getLong或其他东西(?)。 Could anyone shed any light on this? 谁能对此有所启示?

Save current time to SharedPreferences in first Activity class: 将当前时间保存到第一个Activity类的SharedPreferences中:

private void saveCurrentTIme() {
        SharedPreferences sharedpreferences = getSharedPreferences("myAppPref",
            Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putLong("GameTime", System.currentTimeMillis());
        editor.commit();
}

Retrieve saved time from SharedPreferences in second Activity class: 从第二个Activity类的SharedPreferences中检索节省的时间:

    private long getSavedTime() {
            SharedPreferences sharedpreferences = getSharedPreferences("myAppPref", Context.MODE_PRIVATE);
            return sharedpreferences.getLong(Name, 0L);

     }

For comparing if the saved time is passed, you can create something like Timer . 为了比较是否节省了时间,您可以创建类似Timer东西。

You can check this answer for how to do it. 您可以检查此答案以了解操作方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM