Android Java-在For循环中使用处理程序

Android Java-在For循环中使用处理程序,java,android,multithreading,handler,Java,Android,Multithreading,Handler,我有一个for循环,它调用一个函数来下载文件。 每次调用函数时,文件的标题都显示在文本视图中。 问题是文件已下载,但UI冻结,只有在文件下载完成后,UI才会更新,并且仅显示最后一个文件的最后一个标题 for(int i=0; i < Titles.size(); i++){ downloading.setText("Downloading: "+Titles.get(i)); if(!Utils.downloadFile(Mp3s.get(i))){ do

我有一个for循环,它调用一个函数来下载文件。 每次调用函数时,文件的标题都显示在文本视图中。 问题是文件已下载,但UI冻结,只有在文件下载完成后,UI才会更新,并且仅显示最后一个文件的最后一个标题

for(int i=0; i < Titles.size(); i++){

    downloading.setText("Downloading: "+Titles.get(i));
    if(!Utils.downloadFile(Mp3s.get(i))){
        downloading.setText("ERROR Downloading: "+Titles.get(i));

    }

}
for(int i=0;i
我知道我必须使用处理程序或线程来解决这个问题。 但我不知道如何实现它。

您可以尝试使用-类似于:

// Move download logic to separate thread, to avoid freezing UI.
new Thread(new Runnable() {
  @Override
  public void run() {
    for(int i=0; i < Titles.size(); i++) {
      // Those need to be final in order to be used inside 
      // Runnables below.
      final String title = Titles.get(i);

      // When in need to update UI, wrap it in Runnable and
      // pass to runOnUiThread().
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          downloading.setText("Downloading: "+title);
        }
      });

      if(!Utils.downloadFile(Mp3s.get(i))) {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            downloading.setText("ERROR Downloading: "+title);
          }
        });
    }
  }
}).start();
(请注意,上面的代码是手工编写的,没有经过编译,所以可能有问题,但它应该能让您了解如何从这里开始

public class DownloadTask extends AsyncTask<URL, String, Void> {
  // This method will be run off the UI thread, no need to 
  // create separate thread explicitely.
  protected Long doInBackground(URL... titles) {
    for(int i=0; i < titles.length; i++) {
      publishProgress("Downloading " + titles[i]);
      if(!Utils.downloadFile(Mp3s.get(i))) {
        publishProgress("ERROR Downloading: " + titles[i]);
      }
    }
  }

   // This method will be called on the UI thread, so
   // there's no need to call `runOnUiThread()` or use handlers.
   protected void onProgressUpdate(String... progress) {
     downloading.setText(progress[0]);
   }
}