我正在從服務器下載文件。我在下載時顯示進度條。當我試圖下載文件它顯示進度條。它在酒吧中顯示0,但我可以下載文件。我用下面的代碼進度條在下載時無響應
// onPreExecute
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
給出//這是一個問的任務fordownloading
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]));
}
的AsyncTask的// onPostExecute
protected void onPostExecute(final Boolean success) {
dismissDialog(progress_bar_type);}
什麼是你的進度條最大值?默認情況下,它是10000,並將進展值在0..100的範圍內肯定會保持進度接近於0. – laalto
@laalto 我使用的最大值爲100,還有一件事我總是將thelenghtOfFile設置爲-1 – DKV
好。下一個問題:你是如何執行asynctask的? – laalto