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

The following examples show how to use com.google.android.gms.games.Games. 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: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 7 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

  if (requestCode == RC_SIGN_IN) {

    Task<GoogleSignInAccount> task =
        GoogleSignIn.getSignedInAccountFromIntent(intent);

    try {
      GoogleSignInAccount account = task.getResult(ApiException.class);
      onConnected(account);
    } catch (ApiException apiException) {
      String message = apiException.getMessage();
      if (message == null || message.isEmpty()) {
        message = getString(R.string.signin_other_error);
      }

      onDisconnected();

      new AlertDialog.Builder(this)
          .setMessage(message)
          .setNeutralButton(android.R.string.ok, null)
          .show();
    }
  } else if (requestCode == RC_LOOK_AT_MATCHES) {
    // Returning from the 'Select Match' dialog

    if (resultCode != Activity.RESULT_OK) {
      logBadActivityResult(requestCode, resultCode,
          "User cancelled returning from the 'Select Match' dialog.");
      return;
    }

    TurnBasedMatch match = intent
        .getParcelableExtra(Multiplayer.EXTRA_TURN_BASED_MATCH);

    if (match != null) {
      updateMatch(match);
    }

    Log.d(TAG, "Match = " + match);
  } else if (requestCode == RC_SELECT_PLAYERS) {
    // Returning from 'Select players to Invite' dialog

    if (resultCode != Activity.RESULT_OK) {
      // user canceled
      logBadActivityResult(requestCode, resultCode,
          "User cancelled returning from 'Select players to Invite' dialog");
      return;
    }

    // get the invitee list
    ArrayList<String> invitees = intent
        .getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);

    // get automatch criteria
    Bundle autoMatchCriteria;

    int minAutoMatchPlayers = intent.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
    int maxAutoMatchPlayers = intent.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);

    if (minAutoMatchPlayers > 0) {
      autoMatchCriteria = RoomConfig.createAutoMatchCriteria(minAutoMatchPlayers,
          maxAutoMatchPlayers, 0);
    } else {
      autoMatchCriteria = null;
    }

    TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
        .addInvitedPlayers(invitees)
        .setAutoMatchCriteria(autoMatchCriteria).build();

    // Start the match
    mTurnBasedMultiplayerClient.createMatch(tbmc)
        .addOnSuccessListener(new OnSuccessListener<TurnBasedMatch>() {
          @Override
          public void onSuccess(TurnBasedMatch turnBasedMatch) {
            onInitiateMatch(turnBasedMatch);
          }
        })
        .addOnFailureListener(createFailureListener("There was a problem creating a match!"));
    showSpinner();
  }
}
 
Example #2
Source File: StartFragment.java    From chess with Apache License 2.0 6 votes vote down vote up
void loadMatches() {
    if (BuildConfig.DEBUG) Logger.log("StartFramgnet.loadMatches");
    if (getView() == null) return; // not visible
    getView().findViewById(R.id.inbox).setVisibility(View.VISIBLE);
    Games.TurnBasedMultiplayer.loadMatchesByStatus(((Main) getActivity()).getGC(),
            new int[]{TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN,
                    TurnBasedMatch.MATCH_TURN_STATUS_THEIR_TURN})
            .setResultCallback(new ResultCallback<TurnBasedMultiplayer.LoadMatchesResult>() {
                @Override
                public void onResult(final TurnBasedMultiplayer.LoadMatchesResult result) {
                    myTurns.setMatches(result.getMatches().getMyTurnMatches());
                    pending.setMatches(result.getMatches().getTheirTurnMatches());
                    result.release();
                }
            });
}
 
Example #3
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 #4
Source File: GameHelper.java    From dice-heroes with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a GoogleApiClient.Builder for use with @link{#setup}. Normally,
 * you do not have to do this; use this method only if you need to make
 * nonstandard setup (e.g. adding extra scopes for other APIs) on the
 * GoogleApiClient.Builder before calling @link{#setup}.
 */
public GoogleApiClient.Builder createApiClientBuilder() {
    if (mSetupDone) {
        String error = "GameHelper: you called GameHelper.createApiClientBuilder() after "
                + "calling setup. You can only get a client builder BEFORE performing setup.";
        logError(error);
        throw new IllegalStateException(error);
    }

    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(
            mActivity, this, this);

    if (0 != (mRequestedClients & CLIENT_GAMES)) {
        builder.addApi(Games.API, mGamesApiOptions);
        builder.addScope(Games.SCOPE_GAMES);
    }

    if (0 != (mRequestedClients & CLIENT_SNAPSHOT)) {
      builder.addScope(Drive.SCOPE_APPFOLDER);
      builder.addApi(Drive.API);
    }

    mGoogleApiClientBuilder = builder;
    return builder;
}
 
Example #5
Source File: PlayGamesPlugin.java    From play_games with MIT License 6 votes vote down vote up
private void handleSuccess(GoogleSignInAccount acc) {
    currentAccount = acc;
    PlayersClient playersClient = Games.getPlayersClient(registrar.activity(), currentAccount);
    playersClient.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
        @Override
        public void onSuccess(Player player) {
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("type", "SUCCESS");
            successMap.put("id", player.getPlayerId());
            successMap.put("email", currentAccount.getEmail());
            successMap.put("displayName", player.getDisplayName());
            successMap.put("hiResImageUri", player.getHiResImageUri().toString());
            successMap.put("iconImageUri", player.getIconImageUri().toString());
            result(successMap);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            error("ERROR_FETCH_PLAYER_PROFILE", e);
        }
    });
}
 
Example #6
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 #7
Source File: SnapshotCoordinator.java    From Asteroid with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: DrawingActivity.java    From 8bitartist with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "onConnected: sign-in successful.");

    // This is *NOT* required; if you do not register a handler for
    // invitation events, you will get standard notifications instead.
    // Standard notifications may be preferable behavior in many cases.
    Games.Invitations.registerInvitationListener(mGoogleApiClient, this);

    // Get invitation from Bundle
    if (bundle != null) {
        Invitation invitation = bundle.getParcelable(Multiplayer.EXTRA_INVITATION);
        if (invitation != null) {
            onInvitationReceived(invitation);
        }
    }

    updateViewVisibility();
}
 
Example #9
Source File: Game.java    From chess with Apache License 2.0 6 votes vote down vote up
/**
 * Game over
 */
public static void over() {
    int winnerTeam = getWinnerTeam();
    if (!match.isLocal) {
        if (BuildConfig.DEBUG) Logger.log("Game.over state: " + match.getStatus());
        if (match.getStatus() == TurnBasedMatch.MATCH_STATUS_ACTIVE) {
            List<ParticipantResult> result = new ArrayList<ParticipantResult>(players.length);
            for (Player p : players) {
                result.add(new ParticipantResult(p.id,
                        p.team == winnerTeam ? ParticipantResult.MATCH_RESULT_WIN :
                                ParticipantResult.MATCH_RESULT_LOSS,
                        ParticipantResult.PLACING_UNINITIALIZED));
                if (BuildConfig.DEBUG)
                    Logger.log(p.id + " " + (p.team == winnerTeam ? "win" : "loss"));
            }
            Games.TurnBasedMultiplayer.finishMatch(api, match.id, toBytes(), result);
        } else {
            Games.TurnBasedMultiplayer.finishMatch(api, match.id);
        }
        if (UI != null) UI.gameOver(winnerTeam == getPlayer(myPlayerId).team);
    } else {
        if (UI != null) UI.gameOverLocal(getWinner());
    }
}
 
Example #10
Source File: GameServicesMultiplayer.java    From dice-heroes with GNU General Public License v3.0 6 votes vote down vote up
@Override public IFuture<Void> quickMatch(final int playersToInvite, final int variant) {
    if (future != null && !future.isHappened())
        throw new IllegalStateException("called invite players while future of previous invite didn't happened!");
    future = new Future<Void>();
    this.variant = variant;
    activity.getMainHandler().post(new Runnable() {
        @Override public void run() {
            controller = createController();
            RoomConfig config = RoomConfig.builder(controller)
                .setAutoMatchCriteria(RoomConfig.createAutoMatchCriteria(playersToInvite, playersToInvite, 0))
                .setRoomStatusUpdateListener(controller)
                .setMessageReceivedListener(controller)
                .setVariant(variant)
                .build();
            Games.RealTimeMultiplayer.create(client, config);
        }
    });
    return future;
}
 
Example #11
Source File: SoomlaGooglePlus.java    From android-profile with Apache License 2.0 6 votes vote down vote up
@Override
public void submitScore(String leaderboardId, long value, final GameServicesCallbacks.SuccessWithScoreListener submitScoreListener) {
    if (enableGameServices) {
        Games.Leaderboards.submitScoreImmediate(googleApiClient, leaderboardId, value).setResultCallback(new ResultCallback<Leaderboards.SubmitScoreResult>() {
            @Override
            public void onResult(Leaderboards.SubmitScoreResult submitScoreResult) {
                if (submitScoreResult.getStatus().isSuccess()) {
                    submitScoreListener.success(
                            new Score(
                                    new Leaderboard(submitScoreResult.getScoreData().getLeaderboardId(), getProvider(), "", ""), // here is no iconURL and title at this moment
                                    0, // rank is undefined here
                                    SoomlaProfile.getInstance().getStoredUserProfile(getProvider()),
                                    submitScoreResult.getScoreData().getScoreResult(LeaderboardVariant.TIME_SPAN_ALL_TIME).rawScore
                            )
                    );
                } else {
                    submitScoreListener.fail(submitScoreResult.getStatus().getStatusMessage());
                }
            }
        });
    } else {
        submitScoreListener.fail("To use GPGS features, please set `enableGameServices = true` in Google provider initialization parameters.");
    }
}
 
Example #12
Source File: BaseGooglePlayServicesActivity.java    From Onesearch with MIT License 6 votes vote down vote up
private void loadScoreOfLeaderBoardIfLarger(final String leaderboardId, final int currentScore, final String gameDifficulty) {
    Games.Leaderboards.loadCurrentPlayerLeaderboardScore(mGoogleApiClient, leaderboardId, LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(new ResultCallback<Leaderboards.LoadPlayerScoreResult>() {
        @Override
        public void onResult(final Leaderboards.LoadPlayerScoreResult scoreResult) {
            if (isScoreResultValid(scoreResult)) {
                // here you can get the score like this
                int score = (int) scoreResult.getScore().getRawScore();
                if (score > currentScore) {
                    SharedPreferences.Editor editor = getSharedPreferences(ResultsActivity.PREF_NAME, MODE_PRIVATE).edit();
                    editor.putInt(ResultsActivity.SCORE_PREFIX + gameDifficulty, score);
                    editor.apply();
                }
            }
        }
    });
}
 
Example #13
Source File: GameSyncService.java    From Passbook with Apache License 2.0 6 votes vote down vote up
@Override
public SyncService connect(Activity context, int localVersion) {
    mLocalVersion = localVersion;
    if (mSignInAccount == null) {
        Intent intent = mGoogleSignClient.getSignInIntent();
        context.startActivityForResult(intent, CA.AUTH);
    } else {
        mGoogleSignClient.silentSignIn().addOnCompleteListener(context, task -> {
            if (task.isSuccessful()) {
                mSignInAccount = task.getResult();
                mSnapshotClient = Games.getSnapshotsClient(context, mSignInAccount);
                mExecutorService.submit(this::read);
            } else {
                context.startActivityForResult(mGoogleSignClient.getSignInIntent(), CA.AUTH);
            }
        });
    }
    return this;
}
 
Example #14
Source File: SnapshotCoordinator.java    From Trivia-Knowledge with Apache License 2.0 6 votes vote down vote up
@Override
public PendingResult<DeleteSnapshotResult> delete(GoogleApiClient googleApiClient,
                                                  final SnapshotMetadata snapshotMetadata) {
    if (!isAlreadyOpen(snapshotMetadata.getUniqueName()) &&
            !isAlreadyClosing(snapshotMetadata.getUniqueName())) {
        setIsClosing(snapshotMetadata.getUniqueName());
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.delete(googleApiClient, snapshotMetadata),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // deleted files are closed.
                            setClosed(snapshotMetadata.getUniqueName());
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshotMetadata.getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshotMetadata.getUniqueName() +
                " is either open or is busy");
    }
}
 
Example #15
Source File: DrawingActivity.java    From 8bitartist with Apache License 2.0 6 votes vote down vote up
/**
 * When the artist clicks done, all guessing is closed and the turn should be passed to the
 * next person to draw. The artist can do this at any point and the artist's turn is never over
 * until Done is clicked.
 */
private void onDoneClicked() {
    // Increment turn number
    mMatchTurnNumber = mMatchTurnNumber + 1;

    // Choose random word subset and correct word
    mTurnWords = getRandomWordSubset(10);
    mWordIndex = (new Random()).nextInt(mTurnWords.size());

    // Send new turn data to others
    TurnMessage turnMessage = new TurnMessage(mMatchTurnNumber, mTurnWords, mWordIndex);
    sendReliableMessageToOthers(turnMessage);


    // Increment turn achievements
    if (isSignedIn() && checkConfiguration(false)) {
        Games.Achievements.increment(mGoogleApiClient,
                getString(R.string.achievement_5_turns), 1);
        Games.Achievements.increment(mGoogleApiClient,
                getString(R.string.achievement_10_turns), 1);
    }

    beginMyTurn();
    updateViewVisibility();
}
 
Example #16
Source File: Main.java    From chess with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnected(final Bundle bundle) {
    if (BuildConfig.DEBUG) Logger.log("Main.onConnected");
    TurnBasedMatch match;
    if (bundle != null &&
            (match = bundle.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH)) != null) {
        if (gameFragment == null || !gameFragment.isVisible()) {
            if (Game.load(match.getData(), new Match(match), mGoogleApiClient)) {
                startGame(match.getMatchId());
            } else {
                updateApp();
            }
        }
    } else {
        if (startFragment != null && startFragment.isVisible()) startFragment.loadMatches();
    }
    Games.TurnBasedMultiplayer.registerMatchUpdateListener(mGoogleApiClient, this);
}
 
Example #17
Source File: SnapshotCoordinator.java    From Trivia-Knowledge with Apache License 2.0 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> open(GoogleApiClient googleApiClient,
                                              final String filename, boolean createIfNotFound) {
    // check if the file is already open
    if (!isAlreadyOpen(filename)) {
        setIsOpening(filename);
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.open(googleApiClient, filename, createIfNotFound),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // if open failed, set the file to closed, otherwise, keep it open.
                            if (!result.getStatus().isSuccess()) {
                                Log.d(TAG, "Open was not a success: " +
                                        result.getStatus() + " for filename " + filename);
                                setClosed(filename);
                            } else {
                                Log.d(TAG, "Open successful: " + filename);
                            }
                        }
                    });
        } catch (RuntimeException e) {
            // catch runtime exceptions here - they should not happen, but they do.
            // mark the file as closed so it can be attempted to be opened again.
            setClosed(filename);
            throw e;
        }
    } else {
        // a more sophisticated solution could attach this operation to a future
        // that would be triggered by closing the file, but this will at least avoid
        // corrupting the data with non-resolvable conflicts.
        throw new IllegalStateException(filename + " is already open");
    }
}
 
Example #18
Source File: GameOverActivity.java    From ColorPhun with Apache License 2.0 5 votes vote down vote up
public void showLeaderboard(View view) {
    if (isSignedIn()) {
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(),
                getString(R.string.LEADERBOARD_ID)), REQUEST_LEADERBOARD);
    } else {
        showAlert(getString(R.string.signin_help_title), getString(R.string.signin_help));
    }
}
 
Example #19
Source File: GameHelper.java    From FixMath with Apache License 2.0 5 votes vote down vote up
/** Called when we successfully obtain a connection to a client. */
@Override
public void onConnected(Bundle connectionHint) {
    debugLog("onConnected: connected!");

    if (connectionHint != null) {
        debugLog("onConnected: connection hint provided. Checking for invite.");
        Invitation inv = connectionHint
                .getParcelable(Multiplayer.EXTRA_INVITATION);
        if (inv != null && inv.getInvitationId() != null) {
            // retrieve and cache the invitation ID
            debugLog("onConnected: connection hint has a room invite!");
            mInvitation = inv;
            debugLog("Invitation ID: " + mInvitation.getInvitationId());
        }

        // Do we have any requests pending?
        mRequests = Games.Requests
                .getGameRequestsFromBundle(connectionHint);
        if (!mRequests.isEmpty()) {
            // We have requests in onConnected's connectionHint.
            debugLog("onConnected: connection hint has " + mRequests.size()
                    + " request(s)");
        }

        debugLog("onConnected: connection hint provided. Checking for TBMP game.");
        mTurnBasedMatch = connectionHint
                .getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);
    }

    // we're good to go
    succeedSignIn();
}
 
Example #20
Source File: SnapshotCoordinator.java    From Trivia-Knowledge with Apache License 2.0 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> open(GoogleApiClient googleApiClient,
                                              final SnapshotMetadata snapshotMetadata,
                                              int conflictPolicy) {
    // check if the file is already open
    if (!isAlreadyOpen(snapshotMetadata.getUniqueName())) {
        setIsOpening(snapshotMetadata.getUniqueName());
        try {
            return new CoordinatedPendingResult<>(Games.Snapshots.open(
                    googleApiClient, snapshotMetadata, conflictPolicy),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // if open failed, set the file to closed, otherwise, keep it open.
                            if (!result.getStatus().isSuccess()) {
                                Log.d(TAG, "Open was not a success: " +
                                        result.getStatus() + " for filename " +
                                        snapshotMetadata.getUniqueName());
                                setClosed(snapshotMetadata.getUniqueName());
                            } else {
                                Log.d(TAG, "Open was successful: " +
                                        snapshotMetadata.getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshotMetadata.getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshotMetadata.getUniqueName() + " is already open");
    }
}
 
Example #21
Source File: GameHelper.java    From Asteroid with Apache License 2.0 5 votes vote down vote up
/**
 * Called when we successfully obtain a connection to a client.
 */
@Override
public void onConnected(Bundle connectionHint) {
    debugLog("onConnected: connected!");

    if (connectionHint != null) {
        debugLog("onConnected: connection hint provided. Checking for invite.");
        Invitation inv = connectionHint
                .getParcelable(Multiplayer.EXTRA_INVITATION);
        if (inv != null && inv.getInvitationId() != null) {
            // retrieve and cache the invitation ID
            debugLog("onConnected: connection hint has a room invite!");
            mInvitation = inv;
            debugLog("Invitation ID: " + mInvitation.getInvitationId());
        }

        // Do we have any requests pending?
        mRequests = Games.Requests
                .getGameRequestsFromBundle(connectionHint);
        if (!mRequests.isEmpty()) {
            // We have requests in onConnected's connectionHint.
            debugLog("onConnected: connection hint has " + mRequests.size()
                    + " request(s)");
        }

        debugLog("onConnected: connection hint provided. Checking for TBMP game.");
        mTurnBasedMatch = connectionHint
                .getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);
    }

    // we're good to go
    succeedSignIn();
}
 
Example #22
Source File: DrawingActivity.java    From 8bitartist with Apache License 2.0 5 votes vote down vote up
/**
 * Accept an invitation to join an RTMP game
 */
private void acceptInvitation(Invitation invitation) {
    Log.d(TAG, "Got invitation: " + invitation);
    RoomConfig.Builder roomConfigBuilder = RoomConfig.builder(this)
            .setMessageReceivedListener(this)
            .setRoomStatusUpdateListener(this)
            .setInvitationIdToAccept(invitation.getInvitationId());

    Games.RealTimeMultiplayer.join(mGoogleApiClient, roomConfigBuilder.build());
}
 
Example #23
Source File: GameHelper.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/** Called when we successfully obtain a connection to a client. */
@Override
public void onConnected(Bundle connectionHint) {
    debugLog("onConnected: connected!");

    if (connectionHint != null) {
        debugLog("onConnected: connection hint provided. Checking for invite.");
        Invitation inv = connectionHint
                .getParcelable(Multiplayer.EXTRA_INVITATION);
        if (inv != null && inv.getInvitationId() != null) {
            // retrieve and cache the invitation ID
            debugLog("onConnected: connection hint has a room invite!");
            mInvitation = inv;
            debugLog("Invitation ID: " + mInvitation.getInvitationId());
        }

        // Do we have any requests pending?
        mRequests = Games.Requests
                .getGameRequestsFromBundle(connectionHint);
        if (!mRequests.isEmpty()) {
            // We have requests in onConnected's connectionHint.
            debugLog("onConnected: connection hint has " + mRequests.size()
                    + " request(s)");
        }

        debugLog("onConnected: connection hint provided. Checking for TBMP game.");
        mTurnBasedMatch = connectionHint
                .getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);
    }

    // we're good to go
    succeedSignIn();
}
 
Example #24
Source File: GameServicesHelper.java    From dice-heroes with GNU General Public License v3.0 5 votes vote down vote up
private void processLoadScoreResult(LoadPlayerScoreResult result, String leaderboardId, int by, final Future<Boolean> future) {
    if (result.getStatus().isSuccess()) {
        LeaderboardScore score = result.getScore();
        long current = score == null ? 0 : score.getRawScore();
        Games.Leaderboards
            .submitScoreImmediate(
                helper.getApiClient(),
                leaderboardId,
                current + by
            )
            .setResultCallback(new ResultCallback<Leaderboards.SubmitScoreResult>() {
                @Override public void onResult(Leaderboards.SubmitScoreResult submitResult) {
                    final boolean success = submitResult.getStatus().isSuccess();
                    Gdx.app.postRunnable(new Runnable() {
                        @Override public void run() {
                            future.happen(success);
                        }
                    });
                }
            });
    } else {
        Gdx.app.postRunnable(new Runnable() {
            @Override public void run() {
                future.happen(false);
            }
        });
    }
}
 
Example #25
Source File: GameHelper.java    From cordova-google-play-games-services with MIT License 5 votes vote down vote up
/** Called when we successfully obtain a connection to a client. */
@Override
public void onConnected(Bundle connectionHint) {
    debugLog("onConnected: connected!");

    if (connectionHint != null) {
        debugLog("onConnected: connection hint provided. Checking for invite.");
        Invitation inv = connectionHint
                .getParcelable(Multiplayer.EXTRA_INVITATION);
        if (inv != null && inv.getInvitationId() != null) {
            // retrieve and cache the invitation ID
            debugLog("onConnected: connection hint has a room invite!");
            mInvitation = inv;
            debugLog("Invitation ID: " + mInvitation.getInvitationId());
        }

        // Do we have any requests pending?
        mRequests = Games.Requests
                .getGameRequestsFromBundle(connectionHint);
        if (!mRequests.isEmpty()) {
            // We have requests in onConnected's connectionHint.
            debugLog("onConnected: connection hint has " + mRequests.size()
                    + " request(s)");
        }

        debugLog("onConnected: connection hint provided. Checking for TBMP game.");
        mTurnBasedMatch = connectionHint
                .getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);
    }

    // we're good to go
    succeedSignIn();
}
 
Example #26
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: GameHelper.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a GoogleApiClient.Builder for use with @link{#setup}. Normally,
 * you do not have to do this; use this method only if you need to make
 * nonstandard setup (e.g. adding extra scopes for other APIs) on the
 * GoogleApiClient.Builder before calling @link{#setup}.
 */
public GoogleApiClient.Builder createApiClientBuilder() {
    if (mSetupDone) {
        String error = "GameHelper: you called GameHelper.createApiClientBuilder() after "
                + "calling setup. You can only get a client builder BEFORE performing setup.";
        logError(error);
        throw new IllegalStateException(error);
    }

    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(
            mActivity, this, this);

    if (0 != (mRequestedClients & CLIENT_GAMES)) {
        if (mGamesApiOptions != null) {
            builder.addApi(Games.API, mGamesApiOptions);
        } else {
            builder.addApi(Games.API);
        }

        builder.addScope(Games.SCOPE_GAMES);
    }

    if (0 != (mRequestedClients & CLIENT_PLUS)) {
        if (mPlusApiOptions != null) {
            builder.addApi(Plus.API, mPlusApiOptions);
        } else {
            builder.addApi(Plus.API);
        }
        builder.addScope(Plus.SCOPE_PLUS_LOGIN);
    }

    if (0 != (mRequestedClients & CLIENT_APPSTATE)) {
        builder.addApi(AppStateManager.API);
        builder.addScope(AppStateManager.SCOPE_APP_STATE);
    }

    mGoogleApiClientBuilder = builder;
    return builder;
}
 
Example #28
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
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 #29
Source File: PlayGames.java    From shortyz with GNU General Public License v3.0 5 votes vote down vote up
private void onConnected(GoogleSignInAccount googleSignInAccount) {
    Log.d(TAG, "onConnected(): connected to Google APIs");

    this.mAchievementsClient = Games.getAchievementsClient(this.getContext(), googleSignInAccount);
    this.onSignInSucceeded();
    done();
}
 
Example #30
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
@Override
public boolean incrementAchievement(String achievementId, int incNum, float completionPercentage) {
    if (gpgsAchievementIdMapper != null)
        achievementId = gpgsAchievementIdMapper.mapToGsId(achievementId);

    if (achievementId != null && isSessionActive()) {
        // GPGS supports passing a value for incrementation, no need to use completionPercentage
        Games.Achievements.increment(mGoogleApiClient, achievementId, incNum);
        return true;
    } else
        return false;
}