我正在使用此代码获取文件的链接:
private List<String> getFilesList(String path, String idcity){
List<String> files = new ArrayList<String>();
String readJSON = readJSON(path,idcity);
try {
JSONArray jsonArray = new JSONArray(readJSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
files.add(jsonObject.getString("file"));
}
} catch (Exception e) {
Log.e("getFilesList", "Error parsing data ", e);
}
return files;
}
现在我想将所有这些文件下载到SDCard。
我认为这可以使用AsyncTask实现(并显示一个ProgressDialog,其中包含要下载多少文件的信息)。
我正在使用Android API 4,所以我无法使用DownloadManager。
假设链接位于List<String>
,你们能为我提供一些代码吗?
提前致谢!
答案 0 :(得分:3)
在循环浏览网址列表的循环中使用此功能
已编辑:使用早期代码,如果下载的文件大于4MB,则会出现OutOfMemoryError。使用这个,它的效果非常好!
来源:SO Question
public boolean downloadFromUrl(String url, String outputFileName) {
File dir = new File(Environment.getExternalStorageDirectory() + "/"
+ getString(R.string.directory_appBase) + "/");
if (!dir.exists()) {
dir.mkdirs();
}
try {
File file = new File(dir, outputFileName);
URL downloadUrl = new URL(url);
URLConnection ucon = downloadUrl.openConnection();
ucon.connect();
InputStream is = ucon.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte data[] = new byte[1024];
int current = 0;
while ((current = is.read(data)) != -1) {
fos.write(data, 0, current);
}
is.close();
fos.flush();
fos.close();
isFileDownloaded=true;
} catch (IOException e) {
e.printStackTrace();
isFileDownloaded = false;
System.out.println(outputFileName + " not downloaded");
}
if (isFileDownloaded)
System.out.println(outputFileName + " downloaded");
return isFileDownloaded;
}
答案 1 :(得分:1)
只需获取DownloadManager
来源并将其添加到您的项目中。它的依赖性非常少。
DownloadManager
会做很多事情,这些都是你自己实施的主要痛苦。当然,它的调用归结为HTTP GET,但细节中的魔鬼。