2014-12-02 61 views
-2

我有一個類實現runnable與運行功能。Java/Android線程暫停錯誤

@Override 
public void run() 
{ 
    while(running) 
    { 
    // thread code goes here:: 
    threadCode();//// 
    // thread code ends here 
    try 
    { 
     Thread.sleep(10); 
    } 
    catch (InterruptedException e) 
    { 
     e.printStackTrace(); 
    } 
    } 
} 

現在我試圖暫停線程,如果發生什麼事情。 我試圖使用wait()和notify(),但它崩潰了應用程序,之後我想出了使用「running」布爾值並將其設置爲false作爲暫停,然後返回true以恢復。 不幸的是,它仍然崩潰的應用程序。

它給我logcat致命的錯誤。

「無法創建內螺紋處理程序尚未調用Looper.prepare()」

有什麼工作簡單的方法來暫停一個線程? ;/ Thx

編輯: 它根本不是線程。 我發現它崩潰的地方。 它崩潰的警告對話框 這裏是它的代碼:

AlertDialog.Builder builder1 = new AlertDialog.Builder(c); 
     builder1.setTitle("Game over!"); 
    builder1.setMessage("You survived "+secs+"."+msecs+ " seconds."); 
    builder1.setCancelable(false); 
    builder1.setPositiveButton("Replay", 
      new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) 
     { 
      // intialStuff(); 
      dialog.cancel(); 
     } 
    }); 
    builder1.setNegativeButton("Rage quit", 
      new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
      dialog.cancel(); 
     } 
    }); 

    AlertDialog alert11 = builder1.create(); 
    alert11.show(); 

我嘗試在畫布類 運行它,也許它不能在畫布類工作? C是主要活動的背景。

+0

什麼是您的logcat告訴你嗎? – 323go 2014-12-02 14:41:35

回答

0

在Android上,線程的工作方式與常規的基於java的「主」程序不同。從UI線程跨越的線程應該使用Looper來自己使用,否則它們會回退到主UI線程的Looper。對於從run方法內部調用Looper.prepare()的查詢,可能是其中的第一行。然而,從長期可擴展性和正確方法的角度考慮使用Loader或AsynchTask。

+0

你能舉個例子嗎? – hey 2014-12-02 14:45:55

+0

谷歌爲「android asynctask教程」 – Nazgul 2014-12-02 14:46:38

+0

問題不在線程上,它與alertDialog有關,我編輯了主要問題。 ; – hey 2014-12-02 15:29:57

0

有兩個問題,第一個是我在AlertDialog的消息中設置了int值,這導致了崩潰。 解決方法是:

setMessage("You survived "+Integer.toString(secs)+"."+Integer.toString(msecs)+" seconds.") 

第二個問題和主要的,我不得不用投手使線程的AlertDialog不會崩潰。

第二次修復: 創建處理程序。

private Handler threadHandler = new Handler() 
{ 
     public void handleMessage(android.os.Message msg) 
     { 
      //Go to thread function 
      threadCode(); 
     } 
}; 

調用它的運行功能:

@Override 
public void run() 
{ 
    while(true) 
    { 
    try 
    { 
     Thread.sleep(10); 
     //handler 
     if(running) 
     threadHandler.sendEmptyMessage(0); 
    } 
    catch (InterruptedException e) 
    { 
     e.printStackTrace(); 
    } 
    } 
}