com.google.android.gms.games.SnapshotsClient Java Examples

The following examples show how to use com.google.android.gms.games.SnapshotsClient. 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: PlayGameServices.java    From PGSGP with MIT License 6 votes vote down vote up
protected void onMainActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == SignInController.RC_SIGN_IN) {
        GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        signInController.onSignInActivityResult(googleSignInResult);
    } else if (requestCode == AchievementsController.RC_ACHIEVEMENT_UI || requestCode == LeaderboardsController.RC_LEADERBOARD_UI) {
        Pair<Boolean, String> isConnected = connectionController.isConnected();
        godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.PLAYER_CONNECTED, new Object[]{isConnected.first, isConnected.second});
    } else if (requestCode == SavedGamesController.RC_SAVED_GAMES) {
        if (data != null) {
            if (data.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA)) {
                SnapshotMetadata snapshotMetadata = data.getParcelableExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA);
                if (snapshotMetadata != null) {
                    savedGamesController.loadSnapshot(snapshotMetadata.getUniqueName());
                }
            } else if (data.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_NEW)) {
                String unique = new BigInteger(281, new Random()).toString(13);
                String currentSaveName = appActivity.getString(R.string.default_game_name) + unique;

                savedGamesController.createNewSnapshot(currentSaveName);
            }
        }
    }
}
 
Example #2
Source File: Request.java    From play_games with MIT License 6 votes vote down vote up
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 #3
Source File: GameSyncService.java    From Passbook with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: PlayGames.java    From remixed-dungeon with GNU General Public License v3.0 6 votes vote down vote up
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 #5
Source File: PlayGames.java    From remixed-dungeon with GNU General Public License v3.0 6 votes vote down vote up
private void writeToSnapshot(String snapshotId, byte[] content) {

		SnapshotsClient snapshotsClient =
				Games.getSnapshotsClient(Game.instance(), signedInAccount);

		snapshotsClient.open(snapshotId, true, SnapshotsClient.RESOLUTION_POLICY_MOST_RECENTLY_MODIFIED)
				.addOnFailureListener( e -> EventCollector.logException(e))
				.addOnSuccessListener(snapshotDataOrConflict -> {
					if(snapshotDataOrConflict.isConflict()) {
						EventCollector.logException(snapshotDataOrConflict.getConflict().getConflictId());
						//Just remove conflicting snapshot and try again
						snapshotsClient.delete(snapshotDataOrConflict.getConflict().getConflictingSnapshot().getMetadata())
								.addOnCompleteListener(
										task -> PlayGames.this.writeToSnapshot(snapshotId, content)
								);
						return;
					}
					writeSnapshot(snapshotDataOrConflict.getData(),content);
				});
	}
 
Example #6
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
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 #8
Source File: SavedGamesController.java    From PGSGP with MIT License 5 votes vote down vote up
protected void showSavedGamesUI(String title, boolean allowAddBtn, boolean allowDeleteBtn, int maxNumberOfSavedGamesToShow) {
    GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(activity);
    if (connectionController.isConnected().first && googleSignInAccount != null) {
        SnapshotsClient snapshotsClient = Games.getSnapshotsClient(activity, googleSignInAccount);
        Task<Intent> intentTask = snapshotsClient.getSelectSnapshotIntent(title, allowAddBtn, allowDeleteBtn, maxNumberOfSavedGamesToShow);

        intentTask.addOnSuccessListener(new OnSuccessListener<Intent>() {
            @Override
            public void onSuccess(Intent intent) {
                activity.startActivityForResult(intent, RC_SAVED_GAMES);
            }
        });
    }
}
 
Example #9
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
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 #12
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
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 vote down vote up
public Task<Intent> getSelectSnapshotIntent(SnapshotsClient snapshotsClient,
                                            String title,
                                            boolean allowAddButton,
                                            boolean allowDelete,
                                            int maxSnapshots) {
  return snapshotsClient.getSelectSnapshotIntent(title,
      allowAddButton, allowDelete, maxSnapshots);
}
 
Example #14
Source File: MainActivity.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #15
Source File: PlayGames.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
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 #16
Source File: Request.java    From play_games with MIT License 5 votes vote down vote up
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 #17
Source File: Request.java    From play_games with MIT License 5 votes vote down vote up
public void openSnapshot(String snapshotName) {
    SnapshotsClient snapshotsClient = Games.getSnapshotsClient(this.registrar.activity(), currentAccount);
    snapshotsClient.open(snapshotName, true).addOnSuccessListener(generateCallback(snapshotName)).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG, "Could not open snapshot", e);
            error("SNAPSHOT_FAILURE", e);
        }
    });
}
 
Example #18
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 4 votes vote down vote up
public Task<AnnotatedData<SnapshotMetadataBuffer>> load(SnapshotsClient snapshotsClient,
                                                        boolean forceReload) {
  return snapshotsClient.load(forceReload);
}
 
Example #19
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 4 votes vote down vote up
public SnapshotMetadata getSnapshotFromBundle(Bundle bundle) {
  return SnapshotsClient.getSnapshotFromBundle(bundle);
}
 
Example #20
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 4 votes vote down vote up
public Task<Integer> getMaxCoverImageSize(SnapshotsClient snapshotsClient) {
  return snapshotsClient.getMaxCoverImageSize();
}
 
Example #21
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 4 votes vote down vote up
public Task<Integer> getMaxDataSize(SnapshotsClient snapshotsClient) {
  return snapshotsClient.getMaxDataSize();
}