daily pastebin goal
35%
SHARE
TWEET

Untitled

a guest Jan 13th, 2018 129 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import android.app.Activity;
  2. import android.content.Intent;
  3. import android.os.Bundle;
  4. import android.support.annotation.NonNull;
  5. import android.support.annotation.Nullable;
  6. import android.support.v7.app.AlertDialog;
  7. import android.support.v7.app.AppCompatActivity;
  8. import android.util.Log;
  9. import android.view.WindowManager;
  10.  
  11. import com.google.android.gms.auth.api.Auth;
  12. import com.google.android.gms.auth.api.signin.GoogleSignIn;
  13. import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
  14. import com.google.android.gms.auth.api.signin.GoogleSignInClient;
  15. import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
  16. import com.google.android.gms.auth.api.signin.GoogleSignInResult;
  17. import com.google.android.gms.games.Games;
  18. import com.google.android.gms.games.GamesActivityResultCodes;
  19. import com.google.android.gms.games.GamesCallbackStatusCodes;
  20. import com.google.android.gms.games.RealTimeMultiplayerClient;
  21. import com.google.android.gms.games.multiplayer.Invitation;
  22. import com.google.android.gms.games.multiplayer.InvitationCallback;
  23. import com.google.android.gms.games.multiplayer.Multiplayer;
  24. import com.google.android.gms.games.multiplayer.Participant;
  25. import com.google.android.gms.games.multiplayer.realtime.OnRealTimeMessageReceivedListener;
  26. import com.google.android.gms.games.multiplayer.realtime.RealTimeMessage;
  27. import com.google.android.gms.games.multiplayer.realtime.Room;
  28. import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
  29. import com.google.android.gms.games.multiplayer.realtime.RoomStatusUpdateCallback;
  30. import com.google.android.gms.games.multiplayer.realtime.RoomUpdateCallback;
  31. import com.google.android.gms.tasks.OnCompleteListener;
  32. import com.google.android.gms.tasks.OnSuccessListener;
  33. import com.google.android.gms.tasks.Task;
  34.  
  35. import java.util.ArrayList;
  36. import java.util.HashSet;
  37. import java.util.List;
  38.  
  39.  
  40. public class SignIn extends AppCompatActivity {
  41.     private static final String TAG = "SignIn";
  42.     private static final int RC_SIGN_IN = 9001;
  43.     private static final int RC_SELECT_PLAYERS = 9006;
  44.     private static final int RC_WAITING_ROOM = 9007;
  45.     private static final int RC_INVITATION_INBOX = 9008;
  46.     RoomConfig  mJoinedRoomConfig;
  47.     String mMyParticipantId;
  48.     boolean mPlaying = false;
  49.     boolean mWaitingRoomFinishedFromCode = false;
  50.     final static int MIN_PLAYERS = 2;
  51.     HashSet<Integer> pendingMessageSet = new HashSet<>();
  52.     private Activity thisActivity = this;
  53.     private Room mRoom;
  54.     private void signInSilently() {
  55.         if(GoogleSignIn.getLastSignedInAccount(this) == null) {
  56.             GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
  57.             signInClient.silentSignIn().addOnCompleteListener(this, new OnCompleteListener<GoogleSignInAccount>() {
  58.                 @Override
  59.                 public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
  60.                     if (task.isSuccessful()) {
  61.                         GoogleSignInAccount signedInAccount = task.getResult();
  62.                     } else {
  63.                         startSignInIntent();
  64.                     }
  65.                 }
  66.             });
  67.         }
  68.     }
  69.  
  70.     private void startSignInIntent() {
  71.         GoogleSignInClient signInClient = GoogleSignIn.getClient(this, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
  72.         Intent intent = signInClient.getSignInIntent();
  73.         startActivityForResult(intent, RC_SIGN_IN);
  74.     }
  75.  
  76.     @Override
  77.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  78.         super.onActivityResult(requestCode, resultCode, data);
  79.         if (requestCode == RC_SIGN_IN) {
  80.             GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
  81.             if (result.isSuccess()) {
  82.                 GoogleSignInAccount signedInAccount = result.getSignInAccount();
  83.                 checkForInvitation();
  84.             } else {
  85.                 String message = result.getStatus().getStatusMessage();
  86.                 if (message == null || message.isEmpty()) {
  87.                     message = getString(R.string.signin_other_error);
  88.                 }
  89.                 new AlertDialog.Builder(this).setMessage(message).setNeutralButton(android.R.string.ok, null).show();
  90.             }
  91.         }
  92.         if (requestCode == RC_SELECT_PLAYERS) {
  93.             if (resultCode != Activity.RESULT_OK) {
  94.                 // Canceled or some other error.
  95.                 return;
  96.             }
  97.             final ArrayList<String> invitees = data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);
  98.  
  99.             int minAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
  100.             int maxAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
  101.  
  102.             RoomConfig.Builder roomBuilder = RoomConfig.builder(mRoomUpdateCallback)
  103.                     .setOnMessageReceivedListener(mMessageReceivedHandler)
  104.                     .setRoomStatusUpdateCallback(mRoomStatusCallbackHandler)
  105.                     .addPlayersToInvite(invitees);
  106.             if (minAutoPlayers > 0) {
  107.                 roomBuilder.setAutoMatchCriteria(
  108.                         RoomConfig.createAutoMatchCriteria(minAutoPlayers, maxAutoPlayers, 0));
  109.             }
  110.  
  111.             mJoinedRoomConfig = roomBuilder.build();
  112.             Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
  113.                     .create(mJoinedRoomConfig);
  114.         }
  115.         if (requestCode == RC_WAITING_ROOM) {
  116.  
  117.             // Look for finishing the waiting room from code, for example if a
  118.             // "start game" message is received.  In this case, ignore the result.
  119.             if (mWaitingRoomFinishedFromCode) {
  120.                 return;
  121.             }
  122.  
  123.             if (resultCode == Activity.RESULT_OK) {
  124.                 // Start the game!
  125.             } else if (resultCode == Activity.RESULT_CANCELED) {
  126.                 // Waiting room was dismissed with the back button. The meaning of this
  127.                 // action is up to the game. You may choose to leave the room and cancel the
  128.                 // match, or do something else like minimize the waiting room and
  129.                 // continue to connect in the background.
  130.  
  131.                 // in this example, we take the simple approach and just leave the room:
  132.                 Games.getRealTimeMultiplayerClient(thisActivity,
  133.                         GoogleSignIn.getLastSignedInAccount(this))
  134.                         .leave(mJoinedRoomConfig, mRoom.getRoomId());
  135.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  136.             } else if (resultCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
  137.                 // player wants to leave the room.
  138.                 Games.getRealTimeMultiplayerClient(thisActivity,
  139.                         GoogleSignIn.getLastSignedInAccount(this))
  140.                         .leave(mJoinedRoomConfig, mRoom.getRoomId());
  141.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  142.             }
  143.         }
  144.         if (requestCode == RC_INVITATION_INBOX) {
  145.             if (resultCode != Activity.RESULT_OK) {
  146.                 // Canceled or some error.
  147.                 return;
  148.             }
  149.             Invitation invitation = data.getExtras().getParcelable(Multiplayer.EXTRA_INVITATION);
  150.             if (invitation != null) {
  151.                 RoomConfig.Builder builder = RoomConfig.builder(mRoomUpdateCallback)
  152.                         .setInvitationIdToAccept(invitation.getInvitationId());
  153.                 mJoinedRoomConfig = builder.build();
  154.                 Games.getRealTimeMultiplayerClient(thisActivity,
  155.                         GoogleSignIn.getLastSignedInAccount(this))
  156.                         .join(mJoinedRoomConfig);
  157.                 // prevent screen from sleeping during handshake
  158.                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  159.             }
  160.         }
  161.     }
  162.  
  163.     private void startQuickGame() {
  164.         Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(1, 7, 0);
  165.  
  166.         RoomConfig roomConfig =
  167.                 RoomConfig.builder(mRoomUpdateCallback)
  168.                         .setOnMessageReceivedListener(mMessageReceivedHandler)
  169.                         .setRoomStatusUpdateCallback(mRoomStatusCallbackHandler)
  170.                         .setAutoMatchCriteria(autoMatchCriteria)
  171.                         .build();
  172.  
  173.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  174.  
  175.         mJoinedRoomConfig = roomConfig;
  176.  
  177.         Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
  178.                 .create(roomConfig);
  179.     }
  180.  
  181.     private void invitePlayers() {
  182.         Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
  183.                 .getSelectOpponentsIntent(1, 7, true)
  184.                 .addOnSuccessListener(new OnSuccessListener<Intent>() {
  185.                     @Override
  186.                     public void onSuccess(Intent intent) {
  187.                         startActivityForResult(intent, RC_SELECT_PLAYERS);
  188.                     }
  189.                 });
  190.     }
  191.  
  192.     boolean shouldStartGame(Room room) {
  193.         int connectedPlayers = 0;
  194.         for (Participant p : room.getParticipants()) {
  195.             if (p.isConnectedToRoom()) {
  196.                 ++connectedPlayers;
  197.             }
  198.         }
  199.         return connectedPlayers >= MIN_PLAYERS;
  200.     }
  201.  
  202.     boolean shouldCancelGame(Room room) {
  203.         // TODO: Your game-specific cancellation logic here. For example, you might decide to
  204.         // cancel the game if enough people have declined the invitation or left the room.
  205.         // You can check a participant's status with Participant.getStatus().
  206.         // (Also, your UI should have a Cancel button that cancels the game too)
  207.         return false;
  208.     }
  209.  
  210.     private RoomStatusUpdateCallback mRoomStatusCallbackHandler = new RoomStatusUpdateCallback() {
  211.         @Override
  212.         public void onRoomConnecting(@Nullable Room room) {
  213.             // Update the UI status since we are in the process of connecting to a specific room.
  214.         }
  215.  
  216.         @Override
  217.         public void onRoomAutoMatching(@Nullable Room room) {
  218.             // Update the UI status since we are in the process of matching other players.
  219.         }
  220.  
  221.         @Override
  222.         public void onPeerInvitedToRoom(@Nullable Room room, @NonNull List<String> list) {
  223.             // Update the UI status since we are in the process of matching other players.
  224.         }
  225.  
  226.         @Override
  227.         public void onPeerDeclined(@Nullable Room room, @NonNull List<String> list) {
  228.             if (!mPlaying && shouldCancelGame(room)) {
  229.                 Games.getRealTimeMultiplayerClient(thisActivity,
  230.                         GoogleSignIn.getLastSignedInAccount(thisActivity))
  231.                         .leave(mJoinedRoomConfig, room.getRoomId());
  232.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  233.             }
  234.         }
  235.  
  236.         @Override
  237.         public void onPeerJoined(@Nullable Room room, @NonNull List<String> list) {
  238.             // Update UI status indicating new players have joined!
  239.         }
  240.  
  241.         @Override
  242.         public void onPeerLeft(@Nullable Room room, @NonNull List<String> list) {
  243.             if (!mPlaying && shouldCancelGame(room)) {
  244.                 Games.getRealTimeMultiplayerClient(thisActivity,
  245.                         GoogleSignIn.getLastSignedInAccount(thisActivity))
  246.                         .leave(mJoinedRoomConfig, room.getRoomId());
  247.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  248.             }
  249.         }
  250.  
  251.         @Override
  252.         public void onConnectedToRoom(@Nullable Room room) {
  253.             mRoom = room;
  254.             Games.getPlayersClient(thisActivity, GoogleSignIn.getLastSignedInAccount(thisActivity))
  255.                     .getCurrentPlayerId().addOnSuccessListener(new OnSuccessListener<String>() {
  256.                 @Override
  257.                 public void onSuccess(String playerId) {
  258.                     mMyParticipantId = mRoom.getParticipantId(playerId);
  259.                 }
  260.             });
  261.         }
  262.  
  263.         @Override
  264.         public void onDisconnectedFromRoom(@Nullable Room room) {
  265.             Games.getRealTimeMultiplayerClient(thisActivity, GoogleSignIn.getLastSignedInAccount(thisActivity))
  266.                     .leave(mJoinedRoomConfig, room.getRoomId());
  267.             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  268.             // show error message and return to main screen
  269.             mRoom = null;
  270.             mJoinedRoomConfig = null;
  271.         }
  272.  
  273.         @Override
  274.         public void onPeersConnected(@Nullable Room room, @NonNull List<String> list) {
  275.             if (mPlaying) {
  276.                 // add new player to an ongoing game
  277.             } else if (shouldStartGame(room)) {
  278.                 // start game!
  279.             }
  280.         }
  281.  
  282.         @Override
  283.         public void onPeersDisconnected(@Nullable Room room, @NonNull List<String> list) {
  284.             if (mPlaying) {
  285.                 // do game-specific handling of this -- remove player's avatar
  286.                 // from the screen, etc. If not enough players are left for
  287.                 // the game to go on, end the game and leave the room.
  288.             } else if (shouldCancelGame(room)) {
  289.                 // cancel the game
  290.                 Games.getRealTimeMultiplayerClient(thisActivity,
  291.                         GoogleSignIn.getLastSignedInAccount(thisActivity))
  292.                         .leave(mJoinedRoomConfig, room.getRoomId());
  293.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  294.             }
  295.         }
  296.  
  297.         @Override
  298.         public void onP2PConnected(@NonNull String participantId) {
  299.             // Update status due to new peer to peer connection.
  300.         }
  301.  
  302.         @Override
  303.         public void onP2PDisconnected(@NonNull String participantId) {
  304.             // Update status due to  peer to peer connection being disconnected.
  305.         }
  306.     };
  307.  
  308.     private void showWaitingRoom(Room room, int maxPlayersToStartGame) {
  309.         Games.getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
  310.                 .getWaitingRoomIntent(room, maxPlayersToStartGame)
  311.                 .addOnSuccessListener(new OnSuccessListener<Intent>() {
  312.                     @Override
  313.                     public void onSuccess(Intent intent) {
  314.                         startActivityForResult(intent, RC_WAITING_ROOM);
  315.                     }
  316.                 });
  317.     }
  318.  
  319.     private void checkForInvitation() {
  320.         Games.getGamesClient(this, GoogleSignIn.getLastSignedInAccount(this))
  321.                 .getActivationHint()
  322.                 .addOnSuccessListener(
  323.                         new OnSuccessListener<Bundle>() {
  324.                             @Override
  325.                             public void onSuccess(Bundle bundle) {
  326.                                 Invitation invitation = bundle.getParcelable(Multiplayer.EXTRA_INVITATION);
  327.                                 if (invitation != null) {
  328.                                     RoomConfig.Builder builder = RoomConfig.builder(mRoomUpdateCallback)
  329.                                             .setInvitationIdToAccept(invitation.getInvitationId());
  330.                                     mJoinedRoomConfig = builder.build();
  331.                                     Games.getRealTimeMultiplayerClient(thisActivity,
  332.                                             GoogleSignIn.getLastSignedInAccount(thisActivity))
  333.                                             .join(mJoinedRoomConfig);
  334.                                     // prevent screen from sleeping during handshake
  335.                                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  336.                                 }
  337.                             }
  338.                         }
  339.                 );
  340.     }
  341.  
  342.     private InvitationCallback mInvitationCallbackHandler = new InvitationCallback() {
  343.         @Override
  344.         public void onInvitationReceived(@NonNull Invitation invitation) {
  345.             RoomConfig.Builder builder = RoomConfig.builder(mRoomUpdateCallback)
  346.                     .setInvitationIdToAccept(invitation.getInvitationId());
  347.             mJoinedRoomConfig = builder.build();
  348.             Games.getRealTimeMultiplayerClient(thisActivity,
  349.                     GoogleSignIn.getLastSignedInAccount(thisActivity))
  350.                     .join(mJoinedRoomConfig);
  351.             // prevent screen from sleeping during handshake
  352.             getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  353.         }
  354.  
  355.         @Override
  356.         public void onInvitationRemoved(@NonNull String invitationId) {
  357.             // Invitation removed.
  358.         }
  359.     };
  360.  
  361.     private void showInvitationInbox() {
  362.         Games.getInvitationsClient(this, GoogleSignIn.getLastSignedInAccount(this))
  363.                 .getInvitationInboxIntent()
  364.                 .addOnSuccessListener(new OnSuccessListener<Intent>() {
  365.                     @Override
  366.                     public void onSuccess(Intent intent) {
  367.                         startActivityForResult(intent, RC_INVITATION_INBOX);
  368.                     }
  369.                 });
  370.     }
  371.  
  372.     void sendToAllReliably(byte[] message) {
  373.         for (String participantId : mRoom.getParticipantIds()) {
  374.             if (!participantId.equals(mMyParticipantId)) {
  375.                 Task<Integer> task = Games.
  376.                         getRealTimeMultiplayerClient(this, GoogleSignIn.getLastSignedInAccount(this))
  377.                         .sendReliableMessage(message, mRoom.getRoomId(), participantId,
  378.                                 handleMessageSentCallback).addOnCompleteListener(new OnCompleteListener<Integer>() {
  379.                             @Override
  380.                             public void onComplete(@NonNull Task<Integer> task) {
  381.                                 // Keep track of which messages are sent, if desired.
  382.                                 recordMessageToken(task.getResult());
  383.                             }
  384.                         });
  385.             }
  386.         }
  387.     }
  388.  
  389.     synchronized void recordMessageToken(int tokenId) {
  390.         pendingMessageSet.add(tokenId);
  391.     }
  392.  
  393.     private RealTimeMultiplayerClient.ReliableMessageSentCallback handleMessageSentCallback =
  394.             new RealTimeMultiplayerClient.ReliableMessageSentCallback() {
  395.                 @Override
  396.                 public void onRealTimeMessageSent(int statusCode, int tokenId, String recipientId) {
  397.                     // handle the message being sent.
  398.                     synchronized (this) {
  399.                         pendingMessageSet.remove(tokenId);
  400.                     }
  401.                 }
  402.             };
  403.  
  404.     private OnRealTimeMessageReceivedListener mMessageReceivedHandler =
  405.             new OnRealTimeMessageReceivedListener() {
  406.                 @Override
  407.                 public void onRealTimeMessageReceived(@NonNull RealTimeMessage realTimeMessage) {
  408.                     // Handle messages received here.
  409.                     byte[] message = realTimeMessage.getMessageData();
  410.                     // process message contents...
  411.                 }
  412.             };
  413.  
  414.     public void quick_Game() {
  415.         startQuickGame();
  416.     }
  417.  
  418.     @Override
  419.     protected void onResume() {
  420.         super.onResume();
  421.         signInSilently();
  422.     }
  423.  
  424.     @Override
  425.     protected void onCreate(Bundle savedInstanceState) {
  426.         super.onCreate(savedInstanceState);
  427.         setContentView(R.layout.activity_sign_in);
  428.     }
  429.  
  430.     private RoomUpdateCallback mRoomUpdateCallback = new RoomUpdateCallback() {
  431.         @Override
  432.         public void onRoomCreated(int code, @Nullable Room room) {
  433.             // Update UI and internal state based on room updates.
  434.             if (code == GamesCallbackStatusCodes.OK && room != null) {
  435.                 Log.d(TAG, "Room " + room.getRoomId() + " created.");
  436.                 showWaitingRoom(room, 8);
  437.             } else {
  438.                 Log.w(TAG, "Error creating room: " + code);
  439.                 // let screen go to sleep
  440.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  441.  
  442.             }
  443.         }
  444.  
  445.         @Override
  446.         public void onJoinedRoom(int code, @Nullable Room room) {
  447.             // Update UI and internal state based on room updates.
  448.             if (code == GamesCallbackStatusCodes.OK && room != null) {
  449.                 Log.d(TAG, "Room " + room.getRoomId() + " joined.");
  450.                 showWaitingRoom(room, 8);
  451.             } else {
  452.                 Log.w(TAG, "Error joining room: " + code);
  453.                 // let screen go to sleep
  454.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  455.  
  456.             }
  457.         }
  458.  
  459.         @Override
  460.         public void onLeftRoom(int code, @NonNull String roomId) {
  461.             Log.d(TAG, "Left room" + roomId);
  462.         }
  463.  
  464.         @Override
  465.         public void onRoomConnected(int code, @Nullable Room room) {
  466.             if (code == GamesCallbackStatusCodes.OK && room != null) {
  467.                 Log.d(TAG, "Room " + room.getRoomId() + " connected.");
  468.             } else {
  469.                 Log.w(TAG, "Error connecting to room: " + code);
  470.                 // let screen go to sleep
  471.                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  472.  
  473.             }
  474.         }
  475.     };
  476. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top