简体   繁体   中英

How to download a Google Play Games Services Saved Games Snapshot's Data, silently?

I'm trying to use Google's Saved Games feature with Google Play Games Services in my Android app. Google provides sample code how to do so :

private static final int RC_SAVED_GAMES = 9009;
private String mCurrentSaveName = "snapshotTemp";

private void showSavedGamesUI() {
  SnapshotsClient snapshotsClient =
      Games.getSnapshotsClient(this, GoogleSignIn.getLastSignedInAccount(this));
  int maxNumberOfSavedGamesToShow = 5;

  Task<Intent> intentTask = snapshotsClient.getSelectSnapshotIntent(
      "See My Saves", true, true, maxNumberOfSavedGamesToShow);

  intentTask.addOnSuccessListener(new OnSuccessListener<Intent>() {
    @Override
    public void onSuccess(Intent intent) {
      startActivityForResult(intent, RC_SAVED_GAMES);
    }
  });
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent intent) {
  if (intent != null) {
    if (intent.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA)) {
      // Load a snapshot.
      SnapshotMetadata snapshotMetadata =
          intent.getParcelableExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA);
      mCurrentSaveName = snapshotMetadata.getUniqueName();

      // Load the game data from the Snapshot
      // ...
    } else if (intent.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_NEW)) {
      // Create a new snapshot named with a unique string
      String unique = new BigInteger(281, new Random()).toString(13);
      mCurrentSaveName = "snapshotTemp-" + unique;

      // Create the new snapshot
      // ...
    }
  }
}

Obviously, Google wants you to use their provided intent to let the user decide which saved game to load or if a new save game should be created.

I, on the other hand, want to do this decision for the user. However, I'm unable to find a way to return a list of snapshots and to load snapshot data.

Since my game won't require to maintain more than one saved game per user I'm less interested in getting a list of snapshots without an intent (which would be an interesting solution, though) and more in loading a snapshot based on the name of the saved game, silently.

How can I load a snapshot without showing an intent?

The comment of jess leaded me to a solution that is now deprecated. However the person who posted the answer pointed out that there is also a working solution in the CollectAllTheStars sample app that is provided by Google. I was tempted to check this sample app to find out if the Google team has changed the code to fit the new way. For my amuse the comments in that sample app were describing the old deprecated way, still, but the code was changed for my luck.

Inspecting the code gave me ideas, so I came up with this solution:

String serializedSavedGameData;
public void downloadSavedGameData(final String name) {
    if(snapshotsClient != null) {
        snapshotsClient.open(name, true, SnapshotsClient.RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Error while opening snapshot: ", e);
            }
        }).continueWith(new Continuation<SnapshotsClient.DataOrConflict<Snapshot>, byte[]>() {
            @Override
            public byte[] then(@NonNull Task<SnapshotsClient.DataOrConflict<Snapshot>> task) throws Exception {
                Snapshot snapshot = task.getResult().getData();
                // Opening the snapshot was a success and any conflicts have been resolved.
                try {
                    // Extract the raw data from the snapshot.
                    return snapshot.getSnapshotContents().readFully();
                } catch (IOException e) {
                    Log.e(TAG, "Error while reading snapshot: ", e);
                } catch (NullPointerException e) {
                    Log.e(TAG, "Error while reading snapshot: ", e);
                }
                return null;
            }
        }).addOnCompleteListener(new OnCompleteListener<byte[]>() {
            @Override
            public void onComplete(@NonNull Task<byte[]> task) {
                if(task.isSuccessful()) {
                    byte[] data = task.getResult();
                    try {
                        serializedSavedGameData = new String(data, "UTF-16BE");
                    } catch (UnsupportedEncodingException e) {
                        Log.d(TAG, "Failed to deserialize save game data: " + e.getMessage());
                    }
                } else {
                    Exception ex = task.getException();
                    Log.d(TAG, "Failed to load saved game data: " + (ex != null ? ex.getMessage() : "UNKNOWN"));
                }
            }
        });
    }
}

I implemented a simple resolving policy (take the newest saved game on conflicts), but I had no time to hard test all the different cases like conflicts, but it passed my simple tests so far.

Hopefully anybody can profit from this.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM