Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.support.annotation.NonNull;
- import android.support.annotation.Nullable;
- import android.support.v7.app.AlertDialog;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
- import android.view.WindowManager;
- import com.google.android.gms.auth.api.Auth;
- import com.google.android.gms.auth.api.signin.GoogleSignIn;
- import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
- import com.google.android.gms.auth.api.signin.GoogleSignInClient;
- import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
- import com.google.android.gms.auth.api.signin.GoogleSignInResult;
- import com.google.android.gms.games.Games;
- import com.google.android.gms.games.GamesActivityResultCodes;
- import com.google.android.gms.games.GamesCallbackStatusCodes;
- import com.google.android.gms.games.RealTimeMultiplayerClient;
- import com.google.android.gms.games.multiplayer.Invitation;
- import com.google.android.gms.games.multiplayer.InvitationCallback;
- import com.google.android.gms.games.multiplayer.Multiplayer;
- import com.google.android.gms.games.multiplayer.Participant;
- import com.google.android.gms.games.multiplayer.realtime.OnRealTimeMessageReceivedListener;
- import com.google.android.gms.games.multiplayer.realtime.RealTimeMessage;
- import com.google.android.gms.games.multiplayer.realtime.Room;
- import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
- import com.google.android.gms.games.multiplayer.realtime.RoomStatusUpdateCallback;
- import com.google.android.gms.games.multiplayer.realtime.RoomUpdateCallback;
- import com.google.android.gms.tasks.OnCompleteListener;
- import com.google.android.gms.tasks.OnSuccessListener;
- import com.google.android.gms.tasks.Task;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- public class SignIn extends AppCompatActivity {
- private static final String TAG = "SignIn";
- private static final int RC_SIGN_IN = 9001;
- private static final int RC_SELECT_PLAYERS = 9006;
- private static final int RC_WAITING_ROOM = 9007;
- private static final int RC_INVITATION_INBOX = 9008;
- RoomConfig mJoinedRoomConfig;
- String mMyParticipantId;
- boolean mPlaying = false;
- boolean mWaitingRoomFinishedFromCode = false;
- final static int MIN_PLAYERS = 2;
- HashSet<Integer> pendingMessageSet = new HashSet<>();
- private Activity thisActivity = this;
- private Room mRoom;
- private void signInSilently() {
- if(GoogleSignIn.getLastSignedInAccount(this) == null) {
- GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
- signInClient.silentSignIn().addOnCompleteListener(this, new OnCompleteListener<GoogleSignInAccount>() {
- @Override
- public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
- if (task.isSuccessful()) {
- GoogleSignInAccount signedInAccount = task.getResult();
- } else {
- startSignInIntent();
- }
- }
- });
- }
- }
- private void startSignInIntent() {
- GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
- Intent intent = signInClient.getSignInIntent();
- startActivityForResult(intent, RC_SIGN_IN);
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == RC_SIGN_IN) {
- GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
- if (result.isSuccess()) {
- GoogleSignInAccount signedInAccount = result.getSignInAccount();
- checkForInvitation();
- } else {
- String message = result.getStatus().getStatusMessage();
- if (message == null || message.isEmpty()) {
- message = getString(R.string.signin_other_error);
- }
- new AlertDialog.Builder(this).setMessage(message).setNeutralButton(android.R.string.ok, null).show();
- }
- }
- if (requestCode == RC_SELECT_PLAYERS) {
- if (resultCode != Activity.RESULT_OK) {
- // Canceled or some other error.
- return;
- }
- final ArrayList<String> invitees = data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
- int minAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
- int maxAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
- RoomConfig.Builder roomBuilder = RoomConfig.builder(mRoomUpdateCallback)
- .setOnMessageReceivedListener(mMessageReceivedHandler)
- .setRoomStatusUpdateCallback(mRoomStatusCallbackHandler)
- .addPlayersToInvite(invitees);
- if (minAutoPlayers > 0) {
- roomBuilder.setAutoMatchCriteria(
- RoomConfig.createAutoMatchCriteria(minAutoPlayers, maxAutoPlayers, 0));
- }
- mJoinedRoomConfig = roomBuilder.build();
- Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
- .create(mJoinedRoomConfig);
- }
- if (requestCode == RC_WAITING_ROOM) {
- // Look for finishing the waiting room from code, for example if a
- // "start game" message is received. In this case, ignore the result.
- if (mWaitingRoomFinishedFromCode) {
- return;
- }
- if (resultCode == Activity.RESULT_OK) {
- // Start the game!
- } else if (resultCode == Activity.RESULT_CANCELED) {
- // Waiting room was dismissed with the back button. The meaning of this
- // action is up to the game. You may choose to leave the room and cancel the
- // match, or do something else like minimize the waiting room and
- // continue to connect in the background.
- // in this example, we take the simple approach and just leave the room:
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(this))
- .leave(mJoinedRoomConfig, mRoom.getRoomId());
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- } else if (resultCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
- // player wants to leave the room.
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(this))
- .leave(mJoinedRoomConfig, mRoom.getRoomId());
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- if (requestCode == RC_INVITATION_INBOX) {
- if (resultCode != Activity.RESULT_OK) {
- // Canceled or some error.
- return;
- }
- Invitation invitation = data.getExtras().getParcelable(Multiplayer.EXTRA_INVITATION);
- if (invitation != null) {
- RoomConfig.Builder builder = RoomConfig.builder(mRoomUpdateCallback)
- .setInvitationIdToAccept(invitation.getInvitationId());
- mJoinedRoomConfig = builder.build();
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(this))
- .join(mJoinedRoomConfig);
- // prevent screen from sleeping during handshake
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- }
- private void startQuickGame() {
- Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(1, 7, 0);
- RoomConfig roomConfig =
- RoomConfig.builder(mRoomUpdateCallback)
- .setOnMessageReceivedListener(mMessageReceivedHandler)
- .setRoomStatusUpdateCallback(mRoomStatusCallbackHandler)
- .setAutoMatchCriteria(autoMatchCriteria)
- .build();
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- mJoinedRoomConfig = roomConfig;
- Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
- .create(roomConfig);
- }
- private void invitePlayers() {
- Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
- .getSelectOpponentsIntent(1, 7, true)
- .addOnSuccessListener(new OnSuccessListener<Intent>() {
- @Override
- public void onSuccess(Intent intent) {
- startActivityForResult(intent, RC_SELECT_PLAYERS);
- }
- });
- }
- boolean shouldStartGame(Room room) {
- int connectedPlayers = 0;
- for (Participant p : room.getParticipants()) {
- if (p.isConnectedToRoom()) {
- ++connectedPlayers;
- }
- }
- return connectedPlayers >= MIN_PLAYERS;
- }
- boolean shouldCancelGame(Room room) {
- // TODO: Your game-specific cancellation logic here. For example, you might decide to
- // cancel the game if enough people have declined the invitation or left the room.
- // You can check a participant's status with Participant.getStatus().
- // (Also, your UI should have a Cancel button that cancels the game too)
- return false;
- }
- private RoomStatusUpdateCallback mRoomStatusCallbackHandler = new RoomStatusUpdateCallback() {
- @Override
- public void onRoomConnecting(@Nullable Room room) {
- // Update the UI status since we are in the process of connecting to a specific room.
- }
- @Override
- public void onRoomAutoMatching(@Nullable Room room) {
- // Update the UI status since we are in the process of matching other players.
- }
- @Override
- public void onPeerInvitedToRoom(@Nullable Room room, @NonNull List<String> list) {
- // Update the UI status since we are in the process of matching other players.
- }
- @Override
- public void onPeerDeclined(@Nullable Room room, @NonNull List<String> list) {
- if (!mPlaying && shouldCancelGame(room)) {
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(thisActivity))
- .leave(mJoinedRoomConfig, room.getRoomId());
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- @Override
- public void onPeerJoined(@Nullable Room room, @NonNull List<String> list) {
- // Update UI status indicating new players have joined!
- }
- @Override
- public void onPeerLeft(@Nullable Room room, @NonNull List<String> list) {
- if (!mPlaying && shouldCancelGame(room)) {
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(thisActivity))
- .leave(mJoinedRoomConfig, room.getRoomId());
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- @Override
- public void onConnectedToRoom(@Nullable Room room) {
- mRoom = room;
- Games.getPlayersClient(thisActivity, GoogleSignIn.getLastSignedInAccount(thisActivity))
- .getCurrentPlayerId().addOnSuccessListener(new OnSuccessListener<String>() {
- @Override
- public void onSuccess(String playerId) {
- mMyParticipantId = mRoom.getParticipantId(playerId);
- }
- });
- }
- @Override
- public void onDisconnectedFromRoom(@Nullable Room room) {
- Games.getRealTimeMultiplayerClient(thisActivity, GoogleSignIn.getLastSignedInAccount(thisActivity))
- .leave(mJoinedRoomConfig, room.getRoomId());
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- // show error message and return to main screen
- mRoom = null;
- mJoinedRoomConfig = null;
- }
- @Override
- public void onPeersConnected(@Nullable Room room, @NonNull List<String> list) {
- if (mPlaying) {
- // add new player to an ongoing game
- } else if (shouldStartGame(room)) {
- // start game!
- }
- }
- @Override
- public void onPeersDisconnected(@Nullable Room room, @NonNull List<String> list) {
- if (mPlaying) {
- // do game-specific handling of this -- remove player's avatar
- // from the screen, etc. If not enough players are left for
- // the game to go on, end the game and leave the room.
- } else if (shouldCancelGame(room)) {
- // cancel the game
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(thisActivity))
- .leave(mJoinedRoomConfig, room.getRoomId());
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- @Override
- public void onP2PConnected(@NonNull String participantId) {
- // Update status due to new peer to peer connection.
- }
- @Override
- public void onP2PDisconnected(@NonNull String participantId) {
- // Update status due to peer to peer connection being disconnected.
- }
- };
- private void showWaitingRoom(Room room, int maxPlayersToStartGame) {
- Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
- .getWaitingRoomIntent(room, maxPlayersToStartGame)
- .addOnSuccessListener(new OnSuccessListener<Intent>() {
- @Override
- public void onSuccess(Intent intent) {
- startActivityForResult(intent, RC_WAITING_ROOM);
- }
- });
- }
- private void checkForInvitation() {
- Games.getGamesClient(this, GoogleSignIn.getLastSignedInAccount(this))
- .getActivationHint()
- .addOnSuccessListener(
- new OnSuccessListener<Bundle>() {
- @Override
- public void onSuccess(Bundle bundle) {
- Invitation invitation = bundle.getParcelable(Multiplayer.EXTRA_INVITATION);
- if (invitation != null) {
- RoomConfig.Builder builder = RoomConfig.builder(mRoomUpdateCallback)
- .setInvitationIdToAccept(invitation.getInvitationId());
- mJoinedRoomConfig = builder.build();
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(thisActivity))
- .join(mJoinedRoomConfig);
- // prevent screen from sleeping during handshake
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- }
- );
- }
- private InvitationCallback mInvitationCallbackHandler = new InvitationCallback() {
- @Override
- public void onInvitationReceived(@NonNull Invitation invitation) {
- RoomConfig.Builder builder = RoomConfig.builder(mRoomUpdateCallback)
- .setInvitationIdToAccept(invitation.getInvitationId());
- mJoinedRoomConfig = builder.build();
- Games.getRealTimeMultiplayerClient(thisActivity,
- GoogleSignIn.getLastSignedInAccount(thisActivity))
- .join(mJoinedRoomConfig);
- // prevent screen from sleeping during handshake
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- @Override
- public void onInvitationRemoved(@NonNull String invitationId) {
- // Invitation removed.
- }
- };
- private void showInvitationInbox() {
- Games.getInvitationsClient(this, GoogleSignIn.getLastSignedInAccount(this))
- .getInvitationInboxIntent()
- .addOnSuccessListener(new OnSuccessListener<Intent>() {
- @Override
- public void onSuccess(Intent intent) {
- startActivityForResult(intent, RC_INVITATION_INBOX);
- }
- });
- }
- void sendToAllReliably(byte[] message) {
- for (String participantId : mRoom.getParticipantIds()) {
- if (!participantId.equals(mMyParticipantId)) {
- Task<Integer> task = Games.
- getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
- .sendReliableMessage(message, mRoom.getRoomId(), participantId,
- handleMessageSentCallback).addOnCompleteListener(new OnCompleteListener<Integer>() {
- @Override
- public void onComplete(@NonNull Task<Integer> task) {
- // Keep track of which messages are sent, if desired.
- recordMessageToken(task.getResult());
- }
- });
- }
- }
- }
- synchronized void recordMessageToken(int tokenId) {
- pendingMessageSet.add(tokenId);
- }
- private RealTimeMultiplayerClient.ReliableMessageSentCallback handleMessageSentCallback =
- new RealTimeMultiplayerClient.ReliableMessageSentCallback() {
- @Override
- public void onRealTimeMessageSent(int statusCode, int tokenId, String recipientId) {
- // handle the message being sent.
- synchronized (this) {
- pendingMessageSet.remove(tokenId);
- }
- }
- };
- private OnRealTimeMessageReceivedListener mMessageReceivedHandler =
- new OnRealTimeMessageReceivedListener() {
- @Override
- public void onRealTimeMessageReceived(@NonNull RealTimeMessage realTimeMessage) {
- // Handle messages received here.
- byte[] message = realTimeMessage.getMessageData();
- // process message contents...
- }
- };
- public void quick_Game() {
- startQuickGame();
- }
- @Override
- protected void onResume() {
- super.onResume();
- signInSilently();
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_sign_in);
- }
- private RoomUpdateCallback mRoomUpdateCallback = new RoomUpdateCallback() {
- @Override
- public void onRoomCreated(int code, @Nullable Room room) {
- // Update UI and internal state based on room updates.
- if (code == GamesCallbackStatusCodes.OK && room != null) {
- Log.d(TAG, "Room " + room.getRoomId() + " created.");
- showWaitingRoom(room, 8);
- } else {
- Log.w(TAG, "Error creating room: " + code);
- // let screen go to sleep
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- @Override
- public void onJoinedRoom(int code, @Nullable Room room) {
- // Update UI and internal state based on room updates.
- if (code == GamesCallbackStatusCodes.OK && room != null) {
- Log.d(TAG, "Room " + room.getRoomId() + " joined.");
- showWaitingRoom(room, 8);
- } else {
- Log.w(TAG, "Error joining room: " + code);
- // let screen go to sleep
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- @Override
- public void onLeftRoom(int code, @NonNull String roomId) {
- Log.d(TAG, "Left room" + roomId);
- }
- @Override
- public void onRoomConnected(int code, @Nullable Room room) {
- if (code == GamesCallbackStatusCodes.OK && room != null) {
- Log.d(TAG, "Room " + room.getRoomId() + " connected.");
- } else {
- Log.w(TAG, "Error connecting to room: " + code);
- // let screen go to sleep
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
- }
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement