com.google.android.gms.games.snapshot.Snapshot Java Examples
The following examples show how to use
com.google.android.gms.games.snapshot.Snapshot.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SnapshotCoordinator.java From Asteroid with Apache License 2.0 | 6 votes |
@Override public PendingResult<CommitSnapshotResult> commitAndClose(GoogleApiClient googleApiClient, final Snapshot snapshot, SnapshotMetadataChange snapshotMetadataChange) { if (isAlreadyOpen(snapshot.getMetadata().getUniqueName()) && !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) { setIsClosing(snapshot.getMetadata().getUniqueName()); try { return new CoordinatedPendingResult<>( Games.Snapshots.commitAndClose(googleApiClient, snapshot, snapshotMetadataChange), result -> { // even if commit and close fails, the file is closed. Log.d(TAG, "CommitAndClose complete, closing " + snapshot.getMetadata().getUniqueName()); setClosed(snapshot.getMetadata().getUniqueName()); }); } catch (RuntimeException e) { setClosed(snapshot.getMetadata().getUniqueName()); throw e; } } else { throw new IllegalStateException(snapshot.getMetadata().getUniqueName() + " is either closed or is closing"); } }
Example #2
Source File: PlayGames.java From remixed-dungeon with GNU General Public License v3.0 | 6 votes |
private Task<SnapshotMetadata> writeSnapshot(Snapshot snapshot, byte[] data) { // Set the data payload for the snapshot snapshot.getSnapshotContents().writeBytes(data); // Create the change operation SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder() .build(); SnapshotsClient snapshotsClient = Games.getSnapshotsClient(Game.instance(), signedInAccount); // Commit the operation return snapshotsClient.commitAndClose(snapshot, metadataChange); }
Example #3
Source File: GameSyncService.java From Passbook with Apache License 2.0 | 6 votes |
@Override public void send(final byte[] data) { if(data == null || mSignInAccount == null) { return; } mData = data; mSnapshotClient.open(SAVED_DATA, true) .continueWithTask(task -> { Snapshot snapshot = task.getResult().getData(); if (snapshot != null) { snapshot.getSnapshotContents().writeBytes(mData); SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder().build(); return mSnapshotClient.commitAndClose(snapshot, metadataChange); } return null; }) .addOnFailureListener(t -> mListener.onSyncFailed(CA.DATA_SENT)) .addOnCompleteListener(t -> mListener.onSyncProgress(CA.DATA_SENT)); }
Example #4
Source File: GameSyncService.java From Passbook with Apache License 2.0 | 6 votes |
@Override public void read() { if (mSnapshotClient == null) { mListener.onSyncFailed(CA.CONNECTION); } mSnapshotClient.open(SAVED_DATA, true, SnapshotsClient.RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED) .continueWith((task) -> { Snapshot snapshot = task.getResult().getData(); if (snapshot != null) { return snapshot.getSnapshotContents().readFully(); } return null; }) .addOnFailureListener(t -> mListener.onSyncFailed(CA.NO_DATA)) .addOnCompleteListener(t -> { mData = t.getResult(); if (mData.length < 1) { mListener.onSyncFailed(CA.NO_DATA); } else { mListener.onSyncProgress(CA.DATA_RECEIVED); } }); }
Example #5
Source File: GoogleCloudSave.java From dice-heroes with GNU General Public License v3.0 | 6 votes |
private void startResolving(final UserData userData, final Snapshot conflictingSnapshot, final String conflictId, final IConflictResolver resolver) { final SnapshotContents contents = conflictingSnapshot.getSnapshotContents(); final Map server = fromBytes(contents); if (server == null) { contents.writeBytes(toBytes(userData)); Games.Snapshots.resolveConflict(client, conflictId, SNAPSHOT_ID, EMPTY_CHANGE, contents); return; } performUserResolve(server, resolver, new IConflictResolverCallback() { @SuppressWarnings("unchecked") @Override public void onResolved(boolean useLocal) { contents.writeBytes(useLocal ? toBytes(userData) : toBytes(server)); Games.Snapshots .resolveConflict(client, conflictId, SNAPSHOT_ID, EMPTY_CHANGE, contents) .setResultCallback(new ResultCallback<OpenSnapshotResult>() { @Override public void onResult(OpenSnapshotResult result) { if (result.getStatus().getStatusCode() == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT) { startResolving(userData, result.getConflictingSnapshot(), result.getConflictId(), resolver); } } }); } }); }
Example #6
Source File: GoogleCloudSave.java From dice-heroes with GNU General Public License v3.0 | 6 votes |
private void processOpenSnapshotResult(OpenSnapshotResult result, final UserData userData, IConflictResolver resolver) { final Snapshot snapshot = result.getSnapshot(); if (result.getStatus().isSuccess()) { final SnapshotContents contents = snapshot.getSnapshotContents(); final Map server = fromBytes(contents); if (server != null && server.containsKey("uuid") && !server.get("uuid").equals(userData.uuid())) { performUserResolve(server, resolver, new IConflictResolverCallback() { @Override public void onResolved(boolean useLocal) { contents.writeBytes(useLocal ? toBytes(userData) : toBytes(server)); Games.Snapshots.commitAndClose(client, snapshot, EMPTY_CHANGE); } }); } else { contents.writeBytes(toBytes(userData)); Games.Snapshots.commitAndClose(client, snapshot, EMPTY_CHANGE); } } else if (result.getStatus().getStatusCode() == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT) { Snapshot conflictingSnapshot = result.getConflictingSnapshot(); startResolving(userData, conflictingSnapshot, result.getConflictId(), resolver); } }
Example #7
Source File: SnapshotCoordinator.java From Asteroid with Apache License 2.0 | 6 votes |
@Override public PendingResult<OpenSnapshotResult> resolveConflict(GoogleApiClient googleApiClient, String conflictId, final Snapshot snapshot) { if (!isAlreadyOpen(snapshot.getMetadata().getUniqueName()) && !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) { setIsOpening(snapshot.getMetadata().getUniqueName()); try { return new CoordinatedPendingResult<>( Games.Snapshots.resolveConflict(googleApiClient, conflictId, snapshot), result -> { if (!result.getStatus().isSuccess()) { setClosed(snapshot.getMetadata().getUniqueName()); } }); } catch (RuntimeException e) { setClosed(snapshot.getMetadata().getUniqueName()); throw e; } } else { throw new IllegalStateException(snapshot.getMetadata().getUniqueName() + " is already open or is busy"); } }
Example #8
Source File: MainActivity.java From android-basic-samples with Apache License 2.0 | 6 votes |
private void selectSnapshotItem(int requestCode, ArrayList<Snapshot> items, String conflictId, int retryCount) { ArrayList<SnapshotMetadata> snapshotList = new ArrayList<SnapshotMetadata>(items.size()); for (Snapshot m : items) { snapshotList.add(m.getMetadata().freeze()); } Intent intent = new Intent(this, SelectSnapshotActivity.class); intent.putParcelableArrayListExtra(SelectSnapshotActivity.SNAPSHOT_METADATA_LIST, snapshotList); intent.putExtra(SelectSnapshotActivity.CONFLICT_ID, conflictId); intent.putExtra(SelectSnapshotActivity.RETRY_COUNT, retryCount); Log.d(TAG, "Starting activity to select snapshot"); startActivityForResult(intent, requestCode); }
Example #9
Source File: SnapshotCoordinator.java From android-basic-samples with Apache License 2.0 | 6 votes |
@NonNull private OnCompleteListener<SnapshotsClient.DataOrConflict<Snapshot>> createOpenListener(final String filename) { return new OnCompleteListener<SnapshotsClient.DataOrConflict<Snapshot>>() { @Override public void onComplete(@NonNull Task<SnapshotsClient.DataOrConflict<Snapshot>> task) { // if open failed, set the file to closed, otherwise, keep it open. if (!task.isSuccessful()) { Exception e = task.getException(); Log.e(TAG, "Open was not a success for filename " + filename, e); setClosed(filename); } else { SnapshotsClient.DataOrConflict<Snapshot> result = task.getResult(); if (result.isConflict()) { Log.d(TAG, "Open successful: " + filename + ", but with a conflict"); } else { Log.d(TAG, "Open successful: " + filename); } } } }; }
Example #10
Source File: Request.java From play_games with MIT License | 6 votes |
private Map<String, Object> snapshotToMap(Snapshot snapshot) throws IOException { String blob = new String(snapshot.getSnapshotContents().readFully()); Map<String, Object> metadata = new HashMap<>(); metadata.put("title", snapshot.getMetadata().getTitle()); metadata.put("description", snapshot.getMetadata().getDescription()); metadata.put("deviceName", snapshot.getMetadata().getDeviceName()); metadata.put("snapshotId", snapshot.getMetadata().getSnapshotId()); metadata.put("uniqueName", snapshot.getMetadata().getUniqueName()); metadata.put("coverImageAspectRatio", snapshot.getMetadata().getCoverImageAspectRatio()); metadata.put("coverImageUri", snapshot.getMetadata().getCoverImageUri() == null ? null : snapshot.getMetadata().getCoverImageUri().toString()); metadata.put("lastModifiedTimestamp", snapshot.getMetadata().getLastModifiedTimestamp()); Map<String, Object> data = new HashMap<>(); data.put("content", blob); data.put("metadata", metadata); return data; }
Example #11
Source File: Request.java From play_games with MIT License | 6 votes |
public void resolveSnapshotConflict(String snapshotName, String conflictId, String content, Map<String, String> metadata) { if (!hasOnlyAllowedKeys(metadata, "description")) { return; } SnapshotsClient snapshotsClient = Games.getSnapshotsClient(this.registrar.activity(), currentAccount); Snapshot snapshot = pluginRef.getLoadedSnapshot().get(snapshotName); if (snapshot == null) { error("SNAPSHOT_NOT_OPENED", "The snapshot with name " + snapshotName + " was not opened before."); return; } snapshot.getSnapshotContents().writeBytes(content.getBytes()); SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder() .setDescription(metadata.get("description")) .build(); snapshotsClient.resolveConflict(conflictId, snapshot.getMetadata().getSnapshotId(), metadataChange, snapshot.getSnapshotContents()).addOnSuccessListener(generateCallback(snapshotName)).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { error("RESOLVE_SNAPSHOT_CONFLICT_ERROR", e); } }); }
Example #12
Source File: SnapshotCoordinator.java From android-basic-samples with Apache License 2.0 | 5 votes |
public Task<SnapshotsClient.DataOrConflict<Snapshot>> resolveConflict(SnapshotsClient snapshotsClient, String conflictId, String snapshotId, SnapshotMetadataChange snapshotMetadataChange, SnapshotContents snapshotContents) { // Since the unique name of the snapshot is unknown, this resolution method cannot be safely // used. Please use another method of resolution. throw new IllegalStateException("resolving conflicts with ids is not supported."); }
Example #13
Source File: SnapshotCoordinator.java From android-basic-samples with Apache License 2.0 | 5 votes |
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient, final SnapshotMetadata snapshotMetadata, final int conflictPolicy) { final String filename = snapshotMetadata.getUniqueName(); return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() { @Override public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception { return snapshotsClient.open(snapshotMetadata, conflictPolicy) .addOnCompleteListener(createOpenListener(filename)); } }); }
Example #14
Source File: MainActivity.java From android-basic-samples with Apache License 2.0 | 5 votes |
/** * Generates metadata, takes a screenshot, and performs the write operation for saving a * snapshot. */ private Task<SnapshotMetadata> writeSnapshot(Snapshot snapshot) { // Set the data payload for the snapshot. snapshot.getSnapshotContents().writeBytes(mSaveGame.toBytes()); // Save the snapshot. SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder() .setCoverImage(getScreenShot()) .setDescription("Modified data at: " + Calendar.getInstance().getTime()) .build(); return SnapshotCoordinator.getInstance().commitAndClose(mSnapshotsClient, snapshot, metadataChange); }
Example #15
Source File: MainActivity.java From android-basic-samples with Apache License 2.0 | 5 votes |
/** * Conflict resolution for when Snapshots are opened. * * @param requestCode - the request currently being processed. This is used to forward on the * information to another activity, or to send the result intent. * @param result The open snapshot result to resolve on open. * @param retryCount - the current iteration of the retry. The first retry should be 0. * @return The opened Snapshot on success; otherwise, returns null. */ Snapshot processOpenDataOrConflict(int requestCode, SnapshotsClient.DataOrConflict<Snapshot> result, int retryCount) { retryCount++; if (!result.isConflict()) { return result.getData(); } Log.i(TAG, "Open resulted in a conflict!"); SnapshotsClient.SnapshotConflict conflict = result.getConflict(); final Snapshot snapshot = conflict.getSnapshot(); final Snapshot conflictSnapshot = conflict.getConflictingSnapshot(); ArrayList<Snapshot> snapshotList = new ArrayList<Snapshot>(2); snapshotList.add(snapshot); snapshotList.add(conflictSnapshot); // Display both snapshots to the user and allow them to select the one to resolve. selectSnapshotItem(requestCode, snapshotList, conflict.getConflictId(), retryCount); // Since we are waiting on the user for input, there is no snapshot available; return null. return null; }
Example #16
Source File: PlayGames.java From remixed-dungeon with GNU General Public License v3.0 | 5 votes |
public void unpackSnapshotTo(String snapshotId, File readTo, IResult result) { // Get the SnapshotsClient from the signed in account. SnapshotsClient snapshotsClient = Games.getSnapshotsClient(Game.instance(), signedInAccount); // Open the saved game using its name. snapshotsClient.open(snapshotId, true, SnapshotsClient.RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED) .addOnFailureListener(e1 -> EventCollector.logException(e1)) .continueWith(task -> { 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) { EventCollector.logException(e); } result.status(false); return null; }) .addOnCompleteListener(task -> { result.status( Unzip.unzipStream( new ByteArrayInputStream( task.getResult()), readTo.getAbsolutePath(), null)); }); }
Example #17
Source File: SnapshotCoordinator.java From android-basic-samples with Apache License 2.0 | 5 votes |
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient, final String filename, final boolean createIfNotFound) { return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() { @Override public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception { return snapshotsClient.open(filename, createIfNotFound) .addOnCompleteListener(createOpenListener(filename)); } }); }
Example #18
Source File: SnapshotCoordinator.java From android-basic-samples with Apache License 2.0 | 5 votes |
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient, final String filename, final boolean createIfNotFound, final int conflictPolicy) { return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() { @Override public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception { return snapshotsClient.open(filename, createIfNotFound, conflictPolicy) .addOnCompleteListener(createOpenListener(filename)); } }); }
Example #19
Source File: SnapshotCoordinator.java From android-basic-samples with Apache License 2.0 | 5 votes |
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient, final SnapshotMetadata snapshotMetadata) { final String filename = snapshotMetadata.getUniqueName(); return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() { @Override public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception { return snapshotsClient.open(snapshotMetadata) .addOnCompleteListener(createOpenListener(filename)); } }); }
Example #20
Source File: SnapshotCoordinator.java From Trivia-Knowledge with Apache License 2.0 | 5 votes |
@Override public PendingResult<OpenSnapshotResult> resolveConflict(GoogleApiClient googleApiClient, String conflictId, final Snapshot snapshot) { if (!isAlreadyOpen(snapshot.getMetadata().getUniqueName()) && !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) { setIsOpening(snapshot.getMetadata().getUniqueName()); try { return new CoordinatedPendingResult<>( Games.Snapshots.resolveConflict(googleApiClient, conflictId, snapshot), new ResultListener() { @Override public void onResult(Result result) { if (!result.getStatus().isSuccess()) { setClosed(snapshot.getMetadata().getUniqueName()); } } }); } catch (RuntimeException e) { setClosed(snapshot.getMetadata().getUniqueName()); throw e; } } else { throw new IllegalStateException(snapshot.getMetadata().getUniqueName() + " is already open or is busy"); } }
Example #21
Source File: SnapshotCoordinator.java From Trivia-Knowledge with Apache License 2.0 | 5 votes |
@Override public PendingResult<CommitSnapshotResult> commitAndClose(GoogleApiClient googleApiClient, final Snapshot snapshot, SnapshotMetadataChange snapshotMetadataChange) { if (isAlreadyOpen(snapshot.getMetadata().getUniqueName()) && !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) { setIsClosing(snapshot.getMetadata().getUniqueName()); try { return new CoordinatedPendingResult<>( Games.Snapshots.commitAndClose(googleApiClient, snapshot, snapshotMetadataChange), new ResultListener() { @Override public void onResult(Result result) { // even if commit and close fails, the file is closed. Log.d(TAG, "CommitAndClose complete, closing " + snapshot.getMetadata().getUniqueName()); setClosed(snapshot.getMetadata().getUniqueName()); } }); } catch (RuntimeException e) { setClosed(snapshot.getMetadata().getUniqueName()); throw e; } } else { throw new IllegalStateException(snapshot.getMetadata().getUniqueName() + " is either closed or is closing"); } }
Example #22
Source File: SnapshotCoordinator.java From Trivia-Knowledge with Apache License 2.0 | 5 votes |
@Override public void discardAndClose(GoogleApiClient googleApiClient, Snapshot snapshot) { if (isAlreadyOpen(snapshot.getMetadata().getUniqueName()) && !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) { Games.Snapshots.discardAndClose(googleApiClient, snapshot); Log.d(TAG, "Closed " + snapshot.getMetadata().getUniqueName()); setClosed(snapshot.getMetadata().getUniqueName()); } else { throw new IllegalStateException(snapshot.getMetadata().getUniqueName() + " is not open or is busy"); } }
Example #23
Source File: SnapshotCoordinator.java From Asteroid with Apache License 2.0 | 5 votes |
@Override public void discardAndClose(GoogleApiClient googleApiClient, Snapshot snapshot) { if (isAlreadyOpen(snapshot.getMetadata().getUniqueName()) && !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) { Games.Snapshots.discardAndClose(googleApiClient, snapshot); Log.d(TAG, "Closed " + snapshot.getMetadata().getUniqueName()); setClosed(snapshot.getMetadata().getUniqueName()); } else { throw new IllegalStateException(snapshot.getMetadata().getUniqueName() + " is not open or is busy"); } }
Example #24
Source File: GpgsClient.java From gdx-gamesvcs with Apache License 2.0 | 5 votes |
/** * Conflict resolution for when Snapshots are opened. Must be run in an AsyncTask or in a * background thread, */ public Snapshot processSnapshotOpenResult(Snapshots.OpenSnapshotResult result, int retryCount) { Snapshot mResolvedSnapshot = null; retryCount++; int status = result.getStatus().getStatusCode(); Gdx.app.log(GAMESERVICE_ID, "Open Snapshot Result status: " + result.getStatus().getStatusMessage()); if (status == GamesStatusCodes.STATUS_OK) { return result.getSnapshot(); } else if (status == GamesStatusCodes.STATUS_SNAPSHOT_CONFLICT) { Snapshot snapshot = result.getSnapshot(); Snapshot conflictSnapshot = result.getConflictingSnapshot(); // Resolve between conflicts by selecting the highest progress or, if equal, newest of the conflicting // snapshots. mResolvedSnapshot = snapshot; if (snapshot.getMetadata().getProgressValue() < conflictSnapshot.getMetadata().getProgressValue() || snapshot.getMetadata().getProgressValue() == conflictSnapshot.getMetadata().getProgressValue() && snapshot.getMetadata().getLastModifiedTimestamp() < conflictSnapshot.getMetadata().getLastModifiedTimestamp()) { mResolvedSnapshot = conflictSnapshot; } Snapshots.OpenSnapshotResult resolveResult = Games.Snapshots.resolveConflict( mGoogleApiClient, result.getConflictId(), mResolvedSnapshot).await(); if (retryCount < MAX_SNAPSHOT_RESOLVE_RETRIES) { // Recursively attempt again return processSnapshotOpenResult(resolveResult, retryCount); } } // Fail, return null. return null; }
Example #25
Source File: GpgsClient.java From gdx-gamesvcs with Apache License 2.0 | 5 votes |
public boolean loadGameStateSync(String id, ILoadGameStateResponseListener listener) { if (!isSessionActive()) { listener.gsGameStateLoaded(null); return false; } try { // Open the snapshot, creating if necessary Snapshots.OpenSnapshotResult open = Games.Snapshots.open( mGoogleApiClient, id, true).await(); Snapshot snapshot = processSnapshotOpenResult(open, 0); if (snapshot == null) { Gdx.app.log(GAMESERVICE_ID, "Could not open Snapshot."); listener.gsGameStateLoaded(null); return false; } // Read byte[] mSaveGameData = snapshot.getSnapshotContents().readFully(); listener.gsGameStateLoaded(mSaveGameData); return true; } catch (Throwable t) { Gdx.app.error(GAMESERVICE_ID, "Error while reading Snapshot.", t); listener.gsGameStateLoaded(null); return false; } }
Example #26
Source File: GpgsClient.java From gdx-gamesvcs with Apache License 2.0 | 5 votes |
public boolean deleteGameStateSync(String fileId, ISaveGameStateResponseListener success) { if (!isSessionActive()) { if (success != null) success.onGameStateSaved(false, "NO_CONNECTION"); return false; } // Open the snapshot, creating if necessary Snapshots.OpenSnapshotResult open = Games.Snapshots.open( mGoogleApiClient, fileId, false).await(); Snapshot snapshot = processSnapshotOpenResult(open, 0); if (snapshot == null) { Gdx.app.log(GAMESERVICE_ID, "Could not delete game state " + fileId + ": " + open.getStatus().getStatusMessage()); if (success != null) success.onGameStateSaved(false, open.getStatus().getStatusMessage()); return false; } Snapshots.DeleteSnapshotResult deleteResult = Games.Snapshots.delete(mGoogleApiClient, snapshot.getMetadata()).await(); boolean deletionDone = deleteResult.getStatus().isSuccess(); Gdx.app.log(GAMESERVICE_ID, "Delete game state " + fileId + ": " + deletionDone + " - " + open.getStatus().getStatusMessage()); if (success != null) { success.onGameStateSaved(deletionDone, deleteResult.getStatus().getStatusMessage()); } return deletionDone; }
Example #27
Source File: Request.java From play_games with MIT License | 5 votes |
public void saveSnapshot(String snapshotName, String content, Map<String, String> metadata) { if (!hasOnlyAllowedKeys(metadata, "description")) { return; } SnapshotsClient snapshotsClient = Games.getSnapshotsClient(this.registrar.activity(), currentAccount); Snapshot snapshot = pluginRef.getLoadedSnapshot().get(snapshotName); if (snapshot == null) { error("SNAPSHOT_NOT_OPENED", "The snapshot with name " + snapshotName + " was not opened before."); return; } snapshot.getSnapshotContents().writeBytes(content.getBytes()); SnapshotMetadataChange metadataChange = new SnapshotMetadataChange.Builder() .setDescription(metadata.get("description")) .build(); snapshotsClient.commitAndClose(snapshot, metadataChange).addOnSuccessListener(new OnSuccessListener<SnapshotMetadata>() { @Override public void onSuccess(SnapshotMetadata snapshotMetadata) { Map<String, Object> result = new HashMap<>(); result.put("status", true); result(result); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { error("SAVE_SNAPSHOT_ERROR", e); } }); }
Example #28
Source File: MainActivity.java From android-basic-samples with Apache License 2.0 | 4 votes |
private void readSavedGame(Snapshot snapshot) throws IOException { mSaveGame = new SaveGame(snapshot.getSnapshotContents().readFully()); }
Example #29
Source File: GpgsClient.java From gdx-gamesvcs with Apache License 2.0 | 4 votes |
@NonNull public Boolean saveGameStateSync(String id, byte[] gameState, long progressValue, ISaveGameStateResponseListener listener) { if (!isSessionActive()) { if (listener != null) listener.onGameStateSaved(false, "NOT_CONNECTED"); return false; } try { // Open the snapshot, creating if necessary Snapshots.OpenSnapshotResult open = Games.Snapshots.open( mGoogleApiClient, id, true).await(); Snapshot snapshot = processSnapshotOpenResult(open, 0); if (snapshot == null) { Gdx.app.log(GAMESERVICE_ID, "Could not open Snapshot."); if (listener != null) listener.onGameStateSaved(false, "Could not open Snapshot."); return false; } if (progressValue < snapshot.getMetadata().getProgressValue()) { Gdx.app.error(GAMESERVICE_ID, "Progress of saved game state higher than current one. Did not save."); if (listener != null) listener.onGameStateSaved(true, null); return false; } // Write the new data to the snapshot snapshot.getSnapshotContents().writeBytes(gameState); // Change metadata SnapshotMetadataChange.Builder metaDataBuilder = new SnapshotMetadataChange.Builder() .fromMetadata(snapshot.getMetadata()); metaDataBuilder = setSaveGameMetaData(metaDataBuilder, id, gameState, progressValue); SnapshotMetadataChange metadataChange = metaDataBuilder.build(); Snapshots.CommitSnapshotResult commit = Games.Snapshots.commitAndClose( mGoogleApiClient, snapshot, metadataChange).await(); if (!commit.getStatus().isSuccess()) throw new RuntimeException(commit.getStatus().getStatusMessage()); // No failures Gdx.app.log(GAMESERVICE_ID, "Successfully saved gamestate with " + gameState.length + "B"); if (listener != null) listener.onGameStateSaved(true, null); return true; } catch (Throwable t) { Gdx.app.error(GAMESERVICE_ID, "Failed to commit snapshot:" + t.getMessage()); if (listener != null) listener.onGameStateSaved(false, t.getMessage()); return false; } }
Example #30
Source File: PlayGamesPlugin.java From play_games with MIT License | 4 votes |
public Map<String, Snapshot> getLoadedSnapshot() { return this.loadedSnapshots; }