在我的应用程序中,我使用执行器服务从 url 下载文件。现在我想添加一个水平进度条来显示下载进度。但我面临错误。如何在不使用异步任务的情况下在此代码中添加进度条?
private class ExecutorServiceDownload implements Runnable {
private String url;
public ExecutorServiceDownload(String url) {
this.url = url;
}
@Override
public void run() {
dlFile(url);
}
private String dlFile(String surl) {
try {
// I added progressbar here and it didn't download anything
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
URL url = new URL(surl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
input = connection.getInputStream();
String title = URLUtil.guessFileName(String.valueOf(url), null, null);
output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/test_files" + "/" + title);
int contentLength = connection.getContentLength();
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
}
return null;
}
}