您好我需要顯示AsyncTask的摘要進度。我想顯示下載的ProgressBar或ProgressDialog,但我知道該怎麼做,我知道如何顯示對話框,但只有當我下載一個文件時,以及如何下載大量文件時如何。有人可以幫助嗎?AsyncTask ProgressDialog
這裏是我的AyncTaskClass
public class DownloadProgramTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
String path = sUrl[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(path);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100/fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
我創建一個新的類實例爲每個執行,
File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3");
if (!voiceFile.exists()) {
voiceList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath());
Log.e("LINK", MYurl.BASE_URL + a.getVoice());
Log.e("Path voice", "" + voiceFile.getPath());
}
File imgLargeFile = new File(dirImageLarge, a.getId() + ".png");
if (!imgLargeFile.exists()) {
imgLargeList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + "/" + a.getImgLarge(), imgLargeFile.getPath());
}
publishProgress和onProgressUpdate是谷歌的[下載與Android文件 – ligi
可能的複製的東西,顯示ProgressDialog中的進度](http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog) – Distwo
「onProgressUpdate ()'在[Android文檔](http://developer.android.com/reference/android/os/AsyncTask.html)是一樣好作爲任何。 – PPartisan