在Android应用程序中保存打开的关卡,您可以使用SharedPreferences、数据库或文件存储
SharedPreferences是一种轻量级的数据存储方式,适用于存储少量的键值对数据。
import android.content.SharedPreferences;
private static final String PREFS_NAME = "GameSettings";
private static final String KEY_LAST_LEVEL = "lastLevel";
public void saveLastLevel(int level) {
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_LAST_LEVEL, level);
editor.apply();
}
public int getLastLevel() {
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
return sharedPreferences.getInt(KEY_LASTID_LEVEL, 1); // 默认关卡为1
}
// 保存当前关卡
saveLastLevel(currentLevel);
// 读取上次打开的关卡
int lastLevel = getLastLevel();
对于更复杂的数据存储需求,您可以使用SQLite数据库。
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class GameDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "game.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_LEVELS = "levels";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_LAST_LEVEL = "last_level";
public GameDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_LEVELS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_LAST_LEVEL + " INTEGER)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LEVELS);
onCreate(db);
}
}
private GameDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new GameDatabaseHelper(this);
}
public void saveLastLevel(int level) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(GameDatabaseHelper.COLUMN_LAST_LEVEL, level);
db.insertWithOnConflict(GameDatabaseUIHelper.TABLE_LEVELS, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
public int getLastLevel() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(GameDatabaseHelper.TABLE_LEVELA, new String[]{GameDatabaseHelper.COLUMN_LAST_LEVEL}, null, null, null, null, null);
int lastLevel = 1; // 默认关卡为1
if (cursor.moveToFirst()) {
lastLevel = cursor.getInt(cursor.getColumnIndex(GameDatabaseHelper.COLUMN_LAST_LEVEL));
}
cursor.close();
db.close();
return lastLevel;
}
// 保存当前关卡
saveLastLevel(currentLevel);
// 读取上次打开的关卡
int lastLevel = getLastLevel();
领取专属 10元无门槛券
手把手带您无忧上云