2012-02-08 59 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线程中分派更新通知。