gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:16:21 24 4
gpt4 key购买 nike

我有一个 for 循环,它调用一个函数来下载文件。每次调用该函数时,文件的标题都会显示在 TextView 中。问题是文件已下载但 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));

}

}

我知道我必须使用处理程序或线程来解决这个问题。但我不知道如何实现它。

最佳答案

您可以尝试使用 Activity.runOnUiThread() - 类似于:

// 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();

这相当冗长(是的,Java!),而且在我看来,可读性不太好。

另一个解决方案是使用 AsyncTask ,它具有方便的 onProgressUpdate() 方法,旨在更新长时间运行的任务的 UI。它可能看起来像:

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]);
}
}

(请注意,上面的代码是手写的,未编译,因此可能存在错误,但它应该让您了解如何从这里开始。

关于java - Android Java - 在 For 循环中使用处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22437064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com