我想逐个下载Url数组字符串中服务器上的所有图像,这样我就不必从服务器下载图像的zip文件,并在下载后解压缩。
所以我想逐个下载图片并在进度条中显示下载状态。但我在这方面非常失败。我想到了一个想法来制作Url的字符串数组并使用For循环进行下载,但它正在下载String数组的最后一个图像并拒绝或传递数组中的所有其他图像。我想我已经知道发生了什么,但我知道什么是解决方案。
到目前为止我做了什么
protected Void doInBackground(Void... arg0) {
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
String [] imageUrl = {"http://www.androidbegin.com/tutorial/flag/india.png","http://www.androidbegin.com/tutorial/flag/pakistan.png"
,"http://www.androidbegin.com/tutorial/flag/china.png","http://www.androidbegin.com/tutorial/flag/unitedstates.png"};
URL url;
HttpURLConnection urlConnection = null;
for(int i=0;i<imageUrl.length;i++){
url = new URL(imageUrl[i]);
//create the new connection
urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
}
File storagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Test");
storagePath.mkdirs();
String finalName = Long.toString(System.currentTimeMillis());
File myImage = new File(storagePath, finalName + ".png");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(myImage);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
// updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// see http://androidsnippets.com/download-an-http-file-to-sdcard-with-progress-notification
return null;
}
**我想要的是什么:**
- 逐个下载所有图片。
- 下载一张图片后,应将其保存在设备中并更新进度状态。
醇>
请告诉我一些源代码,而不是给我一些想法如何做到这一点。很少有源代码和完整的工作可以理解。
答案 0 :(得分:1)
saving image code
应该在for
循环中。由于此代码在for
循环之外,因此只有最后一个图像在for循环结束时被保存,因此使用了最后一个URL。