简体   繁体   中英

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. I'm trying to use SharedPreferences . I'm not well acquainted with SP and not completely sure how to use it. 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. So here I would getLong or something(?). Could anyone shed any light on this?

Save current time to SharedPreferences in first Activity class:

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:

    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 .

You can check this answer for how to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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