// Called when we receive a real-time message from the network.
// Messages in our game are made up of 2 bytes: the first one is 'F' or 'U'
// indicating
// whether it's a final or interim score. The second byte is the score.
// There is also the
// 'S' message, which indicates that the game should start.
@Override
public void onRealTimeMessageReceived(RealTimeMessage rtm) {
byte[] buf = rtm.getMessageData();
String sender = rtm.getSenderParticipantId();
Log.d(TAG, "Message received: " + (char) buf[0] + "/" + (int) buf[1]);
if (buf[0] == 'F' || buf[0] == 'U') {
// score update.
int existingScore = mParticipantScore.containsKey(sender) ?
mParticipantScore.get(sender) : 0;
int thisScore = (int) buf[1];
if (thisScore > existingScore) {
// this check is necessary because packets may arrive out of
// order, so we
// should only ever consider the highest score we received, as
// we know in our
// game there is no way to lose points. If there was a way to
// lose points,
// we'd have to add a "serial number" to the packet.
mParticipantScore.put(sender, thisScore);
}
// update the scores on the screen
updatePeerScoresDisplay();
// if it's a final score, mark this participant as having finished
// the game
if ((char) buf[0] == 'F') {
mFinishedParticipants.add(rtm.getSenderParticipantId());
}
} else if (buf[0] == 'S') {
// someone else started to play -- so dismiss the waiting room and
// get right to it!
Log.d(TAG, "Starting game because we got a start message.");
dismissWaitingRoom();
startGame(true);
}
}