I'm implementing a simple download manager. The main activity is like this:
For every download button pressed I run a service who have an asynctask for download files and update a progress bar in the notification bar. This is the code of the asynctask:
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
NotificationManager manager;
NotificationCompat.Builder notificationBuilder;
String title="";
int counter = 0;
String url="";
String videoId="";
int totalSize=0;
public DownloadFileFromURL(String title,String videoId){
this.title = title;
this.videoId = videoId;
}
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showNotification();
ItemDownloaded itemDownloaded = new ItemDownloaded(title+".mp3", videoId, String.valueOf(totalSize));
id = db.addDownloadedItem(itemDownloaded);
}
private void showNotification(){
manager = (NotificationManager) getApplicationContext()
.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
/*build the notification*/
notificationBuilder = new NotificationCompat.Builder(
getApplicationContext())
.setWhen(System.currentTimeMillis())
.setContentText("Download in progress")
.setContentTitle(title)
.setAutoCancel(false)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher);
notificationBuilder.setProgress(100, 0, false);
Notification notification = notificationBuilder.build();
manager.notify(title.hashCode() , notification);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
this.url = f_url[0];
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
totalSize = lenghtOfFile;
db.updateTotalSize((int)id, String.valueOf(totalSize));
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
+ "/download/provefile/"+title+".mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
//actualSize = total;
// publishing the progress....
// After this onProgressUpdate will be called
if((counter == 0) || (counter >21)){
publishProgress((int)((total*100)/lenghtOfFile));
if(counter == 0)
counter++;
else
counter = 0;
}else
counter++;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
return "ko";
}
return "ok";
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(Integer... progress) {
// setting progress percentage
//progressBar.setProgress(progress[0]);
//totalLength.setText("/"+humanReadableByteCount(totalSize, true));
//actualLength.setText(humanReadableByteCount(actualSize, true));
notificationBuilder.setProgress(100, progress[0], false);
Notification notification = notificationBuilder.build();
//new Random(System.currentTimeMillis()).nextInt()
manager.notify(title.hashCode() , notification);
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String result) {
// dismiss the dialog after the file was downloaded
notificationBuilder.setProgress(0,0,false);
Notification notification = notificationBuilder.build();
//new Random(System.currentTimeMillis()).nextInt()
manager.notify(title.hashCode() , notification);
if(result.compareTo("ok")==0)
downloadSuccesfullComplete(title);
else
downloadError(title,url);
stopSelf();
/*notificationBuilder.setContentText("Download complete")
.setProgress(0,0,false);
Notification notification = notificationBuilder.build();
//new Random(System.currentTimeMillis()).nextInt()
manager.notify(title.hashCode() , notification);*/
}
}
And this is the notification bar:
Now I want to show , when users press the show button, in another activity inside a ListView all the files in download (so all the running asynctask) and show a progress for every file with the download progress, like this:
How I can do?? I try with a database: in progressUpdate of asynctask I update a column of the table with the actual progress and then in ListView adapter I create an asynctask who execute every second a select sql instruction and update the progress of the progress bar. But I think this isn't a good solution. What do you think??
There is a way to save a reference af all the running asynctask and then in an activity get its and get the progressUpdate?? I thinked to use a subclass of android.Application like a singleton and save in it all the reference to the running asynctask.
Hope I explain all right?? Thank you so much