以下是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();
}
}