I am implementing a modified version of buttonclicker - a generic example of multiplayer android game.
There is an option for the players to go to "Quick Game", in which players seeking multiplayer games are matched randomly. I want the players to wait for 30 secs, and if no matching player is found then the player is asked to play with the computer.
Relevant code:
@Override
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
switch (requestCode) {
...
...
case RC_WAITING_ROOM:
if (responseCode == Activity.RESULT_OK) {
startGame(true);
mSYGameOn = -1;
} else if (responseCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
leaveRoom();
} else if (responseCode == Activity.RESULT_CANCELED) {
// The code that I want to execute
leaveRoom();
gotoMyPlayWithComputerCode()
}
break;
}
super.onActivityResult(requestCode, responseCode, intent);
}
I believe the best way to achieve this is by triggering onActivityResult
at the end of 30 seconds, and the execute my custom code.
The quick game is called by:
@JavascriptInterface
public void multiButtonFunction (String typeButton) {
Intent intent;
switch (typeButton) {
...
...
case "button_quick_game":
// user wants to play against a random opponent right now
startQuickGame();
break;
}
}
Now the code for the QuickGame is below. The Handler
part of the code is what I have added to trigger onActivityResult
, which will inturn exit the quick game screen and will then got to my custom code.:
void startQuickGame() {
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS,
MAX_OPPONENTS, 0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder(this);
rtmConfigBuilder.setMessageReceivedListener(this);
rtmConfigBuilder.setRoomStatusUpdateListener(this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
keepScreenOn();
resetGameVars();
mSYGameOn=1;
Games.RealTimeMultiplayer.create(mGoogleApiClient, rtmConfigBuilder.build());
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run() {
if (mSYGameOn>0) {
setResult(Activity.RESULT_CANCELED, getIntent());
}
}
}, 10000);
}
As can be seen, I tried setResult
but that does not work as the onActivityResult
is not being triggered through it. Am I doing something wrong or is there another way to do the same.
Any help would be appreciated.
thanks
A very simple answer. The handler code should be:
handler.postDelayed(new Runnable()
{
@Override
public void run() {
if (mSYGameOn>0) {
finishActivity(RC_WAITING_ROOM);
}
}
}, 30000);
This fires the onActivityResult()
and treats the room as cancelled,exits the waiting room.
Documentation here