这是一个有点抽象的问题,但想知道是否有任何人可能对我有任何简单的建议或答案。
我有一个 AsyncTask,其中包含一个用于下载几个文本文件的循环,这些文件很小,大约有 12 个。目前下载最多需要 10 秒,这比我想象的要长,有什么我可以做的可以加快下载速度,或者有没有办法同时下载它们而不是一个一个?
这是我用于异步和下载的代码。
@Override
protected Long doInBackground(URL... params) {
try {
// Loop to download
distance dis = new distance();
URL[] urlArray = dis.urlArray();
URL[] urlExtra = dis.urlArrayExtra();
String [] stationName = dis.getStationName();
String [] stationNameExtra = dis.getStationNameExtra();
for (int i = 0; i < urlArray.length; i++) {
String fileName = stationName[i];
File file = new File(sdCard.getAbsolutePath() +
"/Download/" + fileName);
URL url = urlArray[i];
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return null;
}