I'm creating an android app in java, the score in the game changes all the time, multiple times every second. I want to create a save file to be able to keep track of the score when the user comes back to the app, the thing is how should I go about saving it? Seems extremely inefficient to write to the save file multiple times every second whenever the score changes. I thought about saving it in the onDestroy() method, but I heard it's not guaranteed that it would be called...
So what would be a guaranteed way for the score to be saved while not having to access file multiple times every second?
You can have a SharedPreferences used to store data that belong to an app.
To add value to the SharedPreferences
//Whenever you update the score call this function
void updateScore(int score){
SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putInt("score", score);
editor.apply(); //this function will commit asynchronously
}
If you need to get the score at any time call this function.
//Whenever you update the score call this function
public int getScore(){
SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);
return mySharedPref.getInt("score", -1); //-1 is the default value that is returned if the value is not set using putInt
}
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.