需要为安卓游戏保存高分

2022-09-03 03:47:50

这很简单,我需要做的就是为游戏保存一个高分(一个整数)。我假设最简单的方法是将其存储在文本文件中,但我真的不知道如何执行此操作。


答案 1

如果您只需要存储一个整数,那么共享首选项最适合您使用:

//setting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();

要获得首选项:

//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value

当然,替换为高分值的密钥和您偏好的密钥(这些可以是任何内容。将它们设置为可识别和独特的东西是很好的)。"key""myPrefsKey"


答案 2

我认为这个链接会帮助你:

The SharedPreferences class provides a general framework that allows you to save and
retrieve persistent key-value pairs of primitive data types. You can use
SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. 
This data will persist across user sessions (even if your application is killed).

User Preferences

Shared preferences are not strictly for saving "user preferences," such as what ringtone
a user has chosen. If you're interested in creating user preferences for your
application, see PreferenceActivity, which provides an Activity framework for you to 
create user preferences, which will be automatically persisted (using shared preferences).

To get a SharedPreferences object for your application, use one of two methods:

    getSharedPreferences() - Use this if you need multiple preferences files identified
by name, which you specify with the first parameter.
    getPreferences() - Use this if you need only one preferences file for your Activity.
Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:

    Call edit() to get a SharedPreferences.Editor.
    Add values with methods such as putBoolean() and putString().
    Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().

正如我所看到的,保存高分的最佳方式是共享首选项。


推荐