下面是我AsyncTask
从CloudBoost
数据库中下载 PDF 文件。代码工作并下载文件;但是,进度条更新不起作用,因为返回的文件长度为-1
. 有人可以给我一个提示,告诉我如何处理这个问题。
顺便说loading.setProgress(progress[0]);
一下,进度更新方法中的行正在AsyncTask
该类嵌套的类的顶部初始化。
class DownloadPdfFromInternet extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
int count;
try {
URL url = new URL(strings[0]);
URLConnection connection = url.openConnection();
connection.connect();
// get length of file
int lengthOfFile = connection.getContentLength();
Log.d("dozer74", "LengthOf File: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + pubName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
// write data to file
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
loading.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String url) {
loading.dismiss();
openPdfFile();
}
}