进度条+主线程UI更新等待线程完成(Android Java)

时间:2013-01-26 02:16:54

标签: android

我一直在帮助为Android应用程序创建进度条。这里有很多帮助!我有一个问题,虽然我很难修复。当应用程序尝试从联网计算机下载文件时,我显示了一个进度条。这工作得很好,但是我需要更新我的UI,因为发生了错误。我无法更新线程内的UI,我想从getRaceResultsHandler更新UI。不幸的是,它在线程完成之前执行该代码。我尝试了一些没有运气的事情。如果有人可以提供帮助,我会在下面提供我的评论代码示例。

public void getRaceResultsHandler (View view) {

       dialog = new ProgressDialog(this);
       dialog.setCancelable(true);
       dialog.setMessage("Attempting to transfer race files. Please wait...");
       // Set progress style to spinner
       dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
       // display the progressbar
       dialog.show();

       // create a thread for downloading the files

       Thread background = new Thread (new Runnable() {
           public void run() {

                   //The Code here to execute the file download from the networked computer....

                  //Dismiss the progress bar because the download is either completed or failed...
                  dialog.dismiss();                         
           }        
        });
        // start the background thread
        background.start();


              //All Other Code Goes here to update the UI. Shows either an error message or a success based on the results of the download.
//My problem is that this code executes before the background thread is completed. I need it to wait until the thread is completed. 

}

1 个答案:

答案 0 :(得分:0)

尝试使用Handler

关闭该对话框
Handler h = new Handler(); // Create this object in UI Thread



Thread background = new Thread (new Runnable() {
   public void run() {
     h.post(new Runnable()
     {

       public void run()
       {
         dialog.dismiss();
       }

     };
   });

您应该使用AsyncTask代替普通Thread

AsyncTask<Void,Void,Void> aTask = new AsyncTask<Void,Void,Void>()
{

  @Override
  public void onPreExecute()
  {
      // Setup some UI Objects
  }
  @Override
  public void onPostExecute(Void result)
  {
     dialog.dismiss();

  }

  @Override
  protected Void doInBackground(Void...params)
  {
     // your download stuff
     publishProgress(object) // <-- if you want to update the progress of your download task
  }


});

注意:没有尝试我自己,在我朋友的笔记本电脑中没有IDE