2017-01-12 68 views
1

我正在實施buttonclicker的修改版本 - 多人Android遊戲的一個通用示例。如何觸發onActivityResult

玩家可以選擇進入「快速遊戲」,其中尋求多人遊戲的玩家隨機匹配。我希望玩家等待30秒,如果找不到匹配的玩家,則要求玩家玩電腦。

相關代碼:

@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); 
     } 

我認爲實現這一目標的最佳途徑是在30秒結束時觸發onActivityResult,並執行我的自定義代碼。

快速遊戲是由稱爲:

@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; 
     } 
    } 

現在的QuickGame的代碼如下。代碼的Handler部分是我添加了什麼觸發onActivityResult,這將inturn退出快速的遊戲畫面,然後會得到我的自定義代碼:

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); 
    } 

可以看出,我試過setResult但不起作用,因爲onActivityResult未被觸發。我做錯了什麼,或者有另一種方法來做同樣的事情。

任何幫助,將不勝感激。

謝謝

回答

0

一個非常簡單的答案。處理程序代碼應該是:

handler.postDelayed(new Runnable() 
     { 
      @Override 
      public void run() { 
       if (mSYGameOn>0) { 
        finishActivity(RC_WAITING_ROOM); 
       } 
      } 
     }, 30000); 

這將觸發onActivityResult()和對待一房取消,退出了候車室。

文檔here