2012-10-03 40 views
0

檢查LunarLander例如它使用的代碼簡歷抽屜螺紋:SurfaceView和線程已經開始異常

public void surfaceCreated(SurfaceHolder holder) { 
    // start the thread here so that we don't busy-wait in run() 
    // waiting for the surface to be created 
    thread.setRunning(true); 
    thread.start(); 
} 

,這爲最終:

public void surfaceDestroyed(SurfaceHolder holder) { 
    // we have to tell thread to shut down & wait for it to finish, or else 
    // it might touch the Surface after we return and explode 
    boolean retry = true; 
    thread.setRunning(false); 
    while (retry) { 
     try { 
      thread.join(); 
      retry = false; 
     } catch (InterruptedException e) { 
     } 
    } 
} 

但是,當我執行的項目,按回家的按鈕,並恢復它崩潰的應用程序

java.lang.IllegalThreadStateException: Thread already started. 
    at java.lang.Thread.start(Thread.java:1045) 
    at com.example.android.lunarlander.LunarView.surfaceCreated(LunarView.java:862) 
    at android.view.SurfaceView.updateWindow(SurfaceView.java:533) 
    at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:226) 
    at android.view.View.dispatchWindowVisibilityChanged(View.java:5839) 
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945) 
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945) 
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945) 
    at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945) 

我見過這種手法在其他示例中使用後臺線程,但它崩潰。它有什麼問題?

+0

請張貼完整的堆棧跟蹤,包括「引發的」行 – Simon

回答

5

你的線程仍在運行,你不會正確地阻止它,我猜。 你必須中斷你的線程或多數民衆贊成我是如何解決它。因此,而不是使用setRunning和一個布爾值,使你的線程運行,可以使用這樣的事情:

啓動它:

public void surfaceCreated(SurfaceHolder holder) { 
    thread.start(); 
} 

在線程:

public void run() { 

    try { 
     while (true) { 
      // code here 
     } 
    } 
    catch (InterruptedException e) { 
     //disable stuff here 
    } 
} 

,並停止它:

public void surfaceDestroyed(SurfaceHolder holder) { 
    thread.interrupt(); 
} 

我剛剛輸入這個,但它應該給你一個想法。

+0

這是仍然適用?我在InterruptedException中得到一個錯誤,說它無法訪問 – NoobMe

0

你可以這樣說:

@Override 
public void surfaceCreated(SurfaceHolder holder) { 
    if (!thread.isAlive()) { 
     thread.start(); 
    } 
}