【问题标题】:Progress Bar + Main Thread UI Update Wait for Thread to complete (Android Java)进度条 + 主线程 UI 更新等待线程完成(Android Java)
【发布时间】:2013-01-26 10:25:47
【问题描述】:

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

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. 

}

【问题讨论】:

  • AsyncTask 更适合您想要实现的目标。

标签: android


【解决方案1】:

尝试使用 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

【讨论】:

  • 谢谢。异步工作完美。抱歉,对此回复缓慢。
猜你喜欢
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-19
  • 2011-06-09
  • 2020-09-21
相关资源
最近更新 更多