I am using this example to download a file from a server using AsycTask
and to show the downlaod progress in a notification bar. I just modified the doInBackground
method in order to downoad my file:
@Override
protected Void doInBackground(String... Urls) {
//This is where we would do the actual download stuff
//for now I'm just going to loop for 10 seconds
// publishing progress every second
try {
URL url = new URL(Urls[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream( _context.getFilesDir() + "/file_name.apk");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count ;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
// Create the notification in the statusbar
mNotificationHelper.createNotification();
}
protected void onPostExecute(Void result) {
// The task is complete, tell the status bar about it
mNotificationHelper.completed();
}
protected void onProgressUpdate(Integer... progress) {
// This method runs on the UI thread, it receives progress updates
// from the background thread and publishes them to the status bar
mNotificationHelper.progressUpdate(progress[0]);
}
Everything is going ok except that I cannot pull down the notification bar. Why?
Following is picked from the comments.
can you please put an sleep(1000) method before publishProgress and check. just a guess
-
yes, it works, but the download is slowing
Hope you understood the problem. Since you are updating the Notification bar very frequently, you cant be able to pull it down. By increasing the chunk size of data or by updating the progress bar on every 4 or more kb instead of 1kb, you can avoid this problem.
Above will not slow down the data download.
You should override onProgressUpdate method to update your UI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With