2012-02-08 64 views
0

試圖顯示ProgressDialog,但得到: 無法在未調用Looper.prepare()的線程內創建處理程序。不能顯示來自非UI線程的ProgressDialog。如何?

這裏是我的代碼:

public class SocketThread implements Runnable { 
    BufferedReader in; 
    private ProgressDialog dialog; 

    public void run() 
    { 
     socket = null; 

     while (true) 
     { 
      // Loop until connected to server 
      while (socket == null){ 
       dialog = new ProgressDialog(getApplicationContext()); 
       dialog.setMessage("Connecting to " + gatewayString); 
       dialog.setIndeterminate(true); 
       dialog.setCancelable(true); 
       AdvancedMultipleSeriesGraph.this.runOnUiThread(new Runnable() {  
        public void run() { 
         dialog.show(); 

        } 
       }); 

是否可以解決?

回答

4

你可以使用一個處理程序,並使用Handler.post(Runnable)或者,如果你有一個活動的背景下,你可以使用Activity.runOnUiThread(Runnable action)

+0

我不知道「Activity.runOnUiThread(...)」方法。很高興現在知道它。 – Sly 2012-02-08 14:58:01

+0

歡迎你 – Blackbelt 2012-02-08 15:03:46

+0

也許我不理解你,但我的代碼是一樣的,你建議: AdvancedMultipleSeriesGraph.this.runOnUiThread(...) – 2012-02-08 15:08:47

0

NEVER!從與UI線程不同的線程執行UI更新。

解決方案可能是在創建線程時在處理程序上添加引用,以便可以在UI線程中分派更新通知。