1

我一直在为我的 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. 

}
4

1 回答 1

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

于 2013-01-26T02:19:44.397 回答