这是一个抽象的问题,但想知道是否有任何人可能对我有任何简单的建议或答案。
我有一个AsyncTask,它包含一个用于下载一些文本文件的循环,文件很小,其中大约有12个。它目前需要10秒才能下载,这比我想象的要长,是否有任何我可能会做的事情可以加快下载速度,或者是否有办法同时下载它们而不是一个一个人?
继承了Async和下载的代码。
@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;
}
答案 0 :(得分:0)
我想也许你的ByteArrayBuffer瓶颈只能设置为50。
以下是我用来下载某些文件的代码。
@Override
protected String doInBackground(Void... params) {
String filename = "inputAFileName";
HttpURLConnection c;
try {
URL url = new URL("http://someurl/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file = new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
if (file.exists()) {
return "File downloaded!";
} else {
Log.e(TAG, "file not found");
}
} else {
Log.e(TAG, "unable to create folder");
}
}
你可以尝试一下,看看它是否更快。