使用Looper.prepare显示对话框窗口

时间:2013-01-21 07:48:51

标签: android alertdialog progressdialog looper

我想在执行一个工作后显示一个对话框窗口,并且应该显示进度对话框,直到工作完成。所以我尝试在下面的代码中使用线程。

ProgressDialog dialog=new ProgressDialog(SampActivity.this);
                     dialog.setMessage("Please wait..");
                     dialog.setProgress(100);
                     dialog.setMax(5000);
                     dialog.show();
                     Thread progressing = new Thread() 
                       {
                         @Override
                         public void run()
                           {
                                try
                                        {
                                           Thread.sleep(5000);
                                           Looper.prepare();
                                         AlertDialog.Builder 

alertDialogBuilder = new AlertDialog.Builder(SampActivity.this);
                                     alertDialogBuilder.setMessage("finished");
                                     AlertDialog alertDialog = alertDialogBuilder.create();
                                     alertDialog.show();

                                     }
               catch (Exception e) 
               {
                   e.printStackTrace();
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SampActivity.this);
                 alertDialogBuilder.setMessage("Unable to stop SAP.The connection is down.Please retry after sometime.");
                 AlertDialog alertDialog = alertDialogBuilder.create();
                 alertDialog.show();
               }

                       finally
                       {
                           dialog.dismiss();
                       }

                          runOnUiThread(new Runnable(){

                                                @Override
                                                public void run() {
                                                    if(dialog.isShowing())
                                                        dialog.dismiss();
                                                }
                                            });
                       }
                   };       
                 progressing.setPriority(Thread.MAX_PRIORITY );
                 progressing.start();

运行这个程序后程序hangs.i不知道代码中有什么错误。 请帮我搞清楚。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

您无法从非ui线程更新ui ...您可以或使用runOnUiThread执行更新ui的部分:

runOnUiThread(new Runnable() {
public void run() {
    //display dialog
}
});

或者更好地使用AsyncTask ..

private class MyTask extends AsyncTask<URL, Integer, Long> {

   private Context context;

   public MyTask(Context context) {
     this.context = context;
   }

   protected void onPreExecute() {
      progressDialog = ProgressDialog.show(context, "", "msg", true); 
   }

  protected Long doInBackground(URL... urls) {
       //do something
  }

 protected void onPostExecute(Long result) {
     progressDialog.dismiss();  
 }
}