我是Android和Java的新手。我正在尝试下载1000多个图像。我不想在UI
线程中串行执行此操作,因为这会很慢。因此,我使用螺纹和可运行的方式实现了 multi-threading
。
前循环将被称为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());
}
}
确保您不能在mainthread(UI线程)中执行此操作,因为如果您这样做,则应用程序不会响应..然后将被系统杀死,您可以使用ASYNCTASK类是为了做您需要的事情,但我更喜欢使用IntentService但是,您必须使用IntentService,它是一个工作线程(长期操作),但是注意到IntentService在完成当前任务之前不会执行任何操作,如果您需要并行下载它,则必须使用服务,它可以与UI线程一起使用,因此需要异步来执行操作,但要确保与IntentService不同,请确保它一旦完成
而不是为每个下载创建线程,而是创建一个线程并将其用于下载所有图像。
您可以使用asynctask参考:https://developer.android.com/reference/android/android/os/asynctask.html
private class DownloadFilesTask extends AsyncTask<SomeObject, Integer, Long> {
protected Long doInBackground(SomeObject... objs) {
for (final AWSSyncFile f : obj.getFiles()) {
beginDownload(f);
}
}
protected void onPostExecute(Long result) {
//Task Completed
}
new DownloadFilesTask().execute(someObj);
我以前已经开发了一个电子商务应用程序,并且遇到了一个类似的问题,我不得不为每个类别下载一些200多个图像。我这样做的方式是在内部使用循环一个异步和每个下载完成后,使用onprogessupdate()function在相关位置显示图像。我不能共享实际代码,因此我将举一个skeleton示例。
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
}
}