谷歌玩游戏服务与Room数据库

3
我们有一个简单的问答游戏,目前使用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);
}

但问题是,这种方法需要使用字节来写入快照,而我们的数据存储在Room数据库中,我们能否从Room数据库传递数据,还是必须更改本地数据库?

1个回答

1

从问题的描述中,完全不清楚byte[] data是什么。 使用SnapshotsClientSnapshotMetadata(如文档所示,还有其他属性需要设置)。String可以轻松转换为byte[]。您需要一种SaveGame模型来开始 - 可能是一个Room @Entity;然后StringGSON可以提供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);
        ...
    }
    ...
}

这样,从 RoomSnapshotsClient 载入 SaveGame 都不成问题。即使不使用 Room,仍然需要方法来编码/解码快照的负载 - 无论是保存游戏参数还是格式如何。相反,可以定义一个 byte[],其中每个数字都可以表示另一个保存游戏参数;这可能取决于要保存和恢复的负载的复杂程度。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接