2012-09-10 28 views
1

我正在研究Android的opengl遊戲。當用戶放棄遊戲時應該返回到主菜單,但是這個調用是從OpenGl ES線程到UI線程完成的,並且存在一些麻煩。我發現這個職位Pass variables between renderer and another class with queueEvent()並嘗試添加處理程序類下面的代碼:Handler.dispatchMessage從OpenGL線程使用時掛起/崩潰

public class GameActivity extends Activity { 

    private GLSurfaceView gameView; 
    private int menuViewID; 

    private Handler gameOverHandler; 

    public GameActivity() { 
     super(); 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     gameOverHandler = new Handler() { 

      public void handleMessage (Message msg){ 
       handleGameOver(); 
      } 
     }; 
     gameView = new GameView(this, gameOverHandler); 
     menuViewID = R.layout.main; 

     setContentView(menuViewID); 
    } 

    /** Called when the user selects the Send button */ 
    public void startGame(View view) { 
     setContentView(gameView); 
     gameView.setVisibility(View.VISIBLE); 
    } 

    private void handleGameOver() { 
     /** 
     * TODO: switch back to main menu 
     */ 

//  setContentView(menuViewID);   // after this gameView freezes 
//  gameView.setVisibility(View.GONE); // after this application throw an error: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 


    } 
} 

,再後來在OpenGL ES代碼

gameOverHandler.dispatchMessage(Message.obtain(gameOverHandler)); 

但我仍然得到一個凍結或運行時異常(請參閱上面的代碼中的註釋行)。我在這裏失蹤或做錯了什麼?

順便說一句,如何獲得在XML中定義的View實例的引用(請參閱上面的代碼中的menuViewID),或者爲什麼findViewById方法返回NULL

+0

你看着'runOnUiThread'? http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable) – Tim

+0

不,我以前沒有,但它的作品! –

回答

0

你是否必須在UI線程中處理它?我可以使用此代碼處理它只是從我的遊戲類罰款:

Intent myIntent = new Intent(myContext, EndGameActivity.class); 
    ((Activity)getContext()).startActivityForResult(myIntent, 0); 

我剛剛從UI線程活動回活動投的背景,然後開始我的新的活動,從那裏的結果。我發回一個結果,然後在我的UI線程上的活動我趕上結果像這樣:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == 1) { 
     this.finish(); 
    } 

} 
+0

我是對的,你提供了幾個活動:一個用於主菜單,一個用於遊戲本身,另一個用於結果菜單?您的計劃是否只與一項活動一起工作?我有非常小的遊戲,幾個活動太多了,在我看來。 –

+0

是的,我有幾個活動,嗯,我沒有意識到我們正在嘗試在這裏單獨工作......它不會以單一活動的方式工作。在這種情況下,似乎無論是您描述的方式,還是可能將指向您的活動的指針傳遞到非UI線程都必須這樣做。我還沒有嘗試過1次活動。 – WIllJBD

+0

我會在稍後檢查您的解決方案,也許在更大的項目上) 無論如何,感謝您的幫助! –