我们有一个简单的琐事游戏,目前使用Room数据库来存储包括用户进度在内的所有数据。我们现在想整合Google play游戏服务,将游戏进度存储在云端,这样用户在更换设备或重新安装游戏时就可以看到他们的进度。
目前我们在xml文件中有游戏类别和关卡细节,然后在应用程序第一次运行时解析和数据存储在Room数据库中。
我们已经检查了游戏服务的文档,我们知道有这种保存游戏的方法。
private Task<SnapshotMetadata> writeSnapshot(Snapshot snapshot,
byte[] data, Bitmap coverImage, String desc) {
// Set the data payload for the snapshot
snapshot.getSnapshotContents().writeBytes(data);
// Create the change operation
SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder()
.setCoverImage(coverImage)
.setDescription(desc)
.build();
SnapshotsClient snapshotsClient =
Games.getSnapshotsClient(this, GoogleSignIn.getLastSignedInAccount(this));
// Commit the operation
return snapshotsClient.commitAndClose(snapshot, metadataChange);
}
但是问题是,这个方法需要字节来写快照,我们在房间数据库中有数据,我们可以从房间数据库传递数据还是我们必须更改本地数据库?
在写问题时,根本不清楚byte[] data
是什么。使用SnapshotsClient
和SnapshotMetadata
(如文档所示,还有其他属性需要设置)。String
很容易转化为byte[]
。首先,你需要一个SaveGame
的模型——可能是一个房间@Entity
;然后String
&GSON可以提供byte[]
getter/setter:
@Entity(tableName = "savegames")
public class SaveGame {
@PrimaryKey
public int id;
...
/** return a byte-array representation (this is probably what you're asking for). */
public byte[] toByteArray() {
return new Gson().toJson(this).getBytes();
}
/** TODO: initialize instance of {@link SaveGame} from a byte-array representation - so that it will work both ways. */
public void fromByteArray(byte[] bytes) {
SaveGame data = new Gson().fromJson(new String(bytes, StandardCharsets.UTF_8), SaveGame.class);
...
}
}
或者将byte[]
传递给构造函数:
@Entity(tableName = "savegames")
public class SaveGame {
@PrimaryKey
public int id;
...
public SaveGame() {}
@Ignore
public SaveGame(byte[] bytes) {
SaveGame data = new Gson().fromJson(new String(bytes, StandardCharsets.UTF_8), SaveGame.class);
...
}
...
}
同样,从Room
或SnapshotsClient
负载加载SaveGame
都没有问题。即使在不使用Room的情况下,我们仍然需要一些方法来编码/解码快照的有效载荷——无论保存游戏参数或格式如何。相反,我们可以定义一个byte[]
,其中每个数字可以代表另一个保存游戏参数;这可能取决于要保存和恢复的有效负载有多复杂。