我正在从服务器下载文件。我想在下载时显示进度条。当我尝试下载文件时,它会显示进度条。它在栏中显示 0,但我可以下载文件。我使用的代码如下
//onPreExecute
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
//这是一个下载任务
protected String doInBackground(String... arg0) {
int bufferLength = 0;
try {
//geting connection
URL url = new URL( weburl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
// getting file length
int lenghtOfFile = urlConnection.getContentLength();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.extension");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
long total = 0;
while ( (bufferLength = inputStream.read(buffer))!= -1) {
total += bufferLength ;
//progress
publishProgress(""+(int)((total*100)/lenghtOfFile));
fileOutput.write(buffer, 0, bufferLength);
}
我使用 onProgressUpdate 来显示结果但没有用。它仍然只有 0
protected void onProgressUpdate(String...values) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(values[0]));
}
//onPostExecute
protected void onPostExecute(final Boolean success) {
dismissDialog(progress_bar_type);}