我正在研究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
?
你看着'runOnUiThread'? http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable) – Tim
不,我以前沒有,但它的作品! –