我是Android和Java的新手。我想下载1000多张图片。我不想在UI
线程中连续地这样做,因为这样做会很慢。因此,我使用线程实现了multi-threading
,并以下面的方式运行。
for-循环将被调用1000次以上。那么,这是实现这一目标的有效途径吗?OS
会按照自己的方式管理线程池吗?
private void syncS3Data() {
tStart = System.currentTimeMillis();
try {
for (final AWSSyncFile f : awsSyncData.getFiles()) {
new Thread(new Runnable() {
@Override
public void run() {
beginDownload(f);
}
}).start();
}
} catch (Exception ex) {
progressDialog.dismiss();
showMessage("Error:" + ex.getStackTrace().toString());
}
}
发布于 2017-12-05 13:16:02
当然,您不能在MainThread (UI线程)中这样做,因为如果您这样做了,应用程序将不会响应。然后它将被系统杀死,您可以使用AsyncTask类来完成您需要的操作,但是我更喜欢使用intentservice --但是您必须使用Intentservice --它是一个工作线程(长操作),但是要注意,intentservice在完成当前任务之前不会执行任何操作,如果您需要并行下载它,那么您必须使用它与UI线程一起工作,所以您需要asyncTask来执行操作,但是要确保调用stopSelf()不像intentService,它一旦完成就会停止。
发布于 2017-12-05 13:19:49
我以前开发过一个电子商务应用程序,也遇到过一个类似的问题,我不得不下载一些200+图像给每个category.The,我所做的就是在AsyncTask中使用一个循环,每次下载完成后,图像被使用onProgessUpdate()功能显示在相关的地方,我不能分享实际的代码,所以我将给出一个基本的例子。
public class DownloadImages extends AsyncTask<String,String,String>
{
File image;
protected String doInBackground(String... params)
{
//download the image here and lets say its stored in the variable file
//call publishProgress() to run onProgressUpdate()
}
protected void onProgressUpdate(String... values)
{
//use the image in variable file to update the UI
}
}
https://stackoverflow.com/questions/47654358
复制相似问题