The following example shows you how to:
- download a file
- display the progress in a progress dialog
- use AsyncTask
- create a temporary file
I've used this code in my app Moustachify Everything. Initially, the app didn't display the progress bar and it was annoying because you never know if it was actually doing anything.
it's a bit lengthy, but I assure you it's worth it for the user once you see it in action.
01.
/**
02.
* Downloads file from URL and does something with it.
03.
*/
04.
private
void
downloadFile(String url) {
05.
final
ProgressDialog progressDialog =
new
ProgressDialog(
this
);
06.
07.
new
AsyncTask<string, integer,=
""
file=
""
>() {
08.
private
Exception m_error =
null
;
09.
10.
@Override
11.
protected
void
onPreExecute() {
12.
progressDialog.setMessage(
"Downloading ..."
);
13.
progressDialog.setCancelable(
false
);
14.
progressDialog.setMax(
100
);
15.
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
16.
17.
progressDialog.show();
18.
}
19.
20.
@Override
21.
protected
File doInBackground(String... params) {
22.
URL url;
23.
HttpURLConnection urlConnection;
24.
InputStream inputStream;
25.
int
totalSize;
26.
int
downloadedSize;
27.
byte
[] buffer;
28.
int
bufferLength;
29.
30.
File file =
null
;
31.
FileOutputStream fos =
null
;
32.
33.
try
{
34.
url =
new
URL(params[
0
]);
35.
urlConnection = (HttpURLConnection) url.openConnection();
36.
37.
urlConnection.setRequestMethod(
"GET"
);
38.
urlConnection.setDoOutput(
true
);
39.
urlConnection.connect();
40.
41.
file = File.createTempFile(
"Mustachify"
,
"download"
);
42.
fos =
new
FileOutputStream(file);
43.
inputStream = urlConnection.getInputStream();
44.
45.
totalSize = urlConnection.getContentLength();
46.
downloadedSize =
0
;
47.
48.
buffer =
new
byte
[
1024
];
49.
bufferLength =
0
;
50.
51.
// Read through the input buffer and write the contents to the file
52.
while
((bufferLength = inputStream.read(buffer)) >
0
) {
53.
fos.write(buffer,
0
, bufferLength);
54.
downloadedSize += bufferLength;
55.
publishProgress(downloadedSize, totalSize);
56.
}
57.
58.
fos.close();
59.
inputStream.close();
60.
61.
return
file;
62.
}
63.
catch
(MalformedURLException e) {
64.
e.printStackTrace();
65.
m_error = e;
66.
}
67.
catch
(IOException e) {
68.
e.printStackTrace();
69.
m_error = e;
70.
}
71.
72.
return
null
;
73.
}
74.
75.
protected
void
onProgressUpdate(Integer... values) {
76.
progressDialog.setProgress((
int
) ((values[
0
] / (
float
) values[
1
]) *
100
));
77.
};
78.
79.
@Override
80.
protected
void
onPostExecute(File file) {
81.
// If there was an error, do something informative with it.
82.
if
(m_error !=
null
) {
83.
m_error.printStackTrace();
84.
return
;
85.
}
86.
87.
progressDialog.hide();
88.
89.
// You probably want to do something else with this
90.
file.delete();
91.
}
92.
}.execute(url);
93.
} </string,>