【问题标题】:Android : How to pause and resume Download using HttpUrlConnection?Android:如何使用 HttpUrlConnection 暂停和恢复下载?
【发布时间】:2017-12-27 03:11:39
【问题描述】:
我想为 android 做一个下载管理器 我想知道如何添加
暂停和恢复功能我正在使用android的HttpUrlConnection类
获取数据。我还想知道如何访问从 HttpUrlConnection.getInputStream() 获得的 InputStream,由于 Internet 连接(比如用户关闭 Internet 连接)而中断。
任何示例代码都会有所帮助
【问题讨论】:
标签:
android
httpurlconnection
android-download-manager
download-manager
【解决方案1】:
下载器示例here
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(ISSUE_DOWNLOAD_STATUS.intValue()==ECMConstant.ECM_DOWNLOADING){
File file=new File(DESTINATION_PATH);
if(file.exists()){
downloaded = (int) file.length();
connection.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
}else{
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
}
connection.setDoInput(true);
connection.setDoOutput(true);
progressBar.setMax(connection.getContentLength());
in = new BufferedInputStream(connection.getInputStream());
fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
downloaded += x;
progressBar.setProgress(downloaded);
}
致谢:https://stackoverflow.com/users/705297/pomatu