I would suggest using IntentServices:
public class FileDownloader extends IntentService {
private static final String TAG = FileDownloader.class.getName();
public FileDownloader() {
super("FileDownloader");
}
@Override
protected void onHandleIntent(Intent intent) {
String fileName = intent.getStringExtra("Filename");
String folderPath = intent.getStringExtra("Path");
String callBackIntent = intent
.getStringExtra("CallbackString");
// Code for downloading
// When you want to update progress call the sendCallback method
}
private void sendCallback(String CallbackString, String path,
int progress) {
Intent i = new Intent(callBackIntent);
i.putExtra("Filepath", path);
i.putExtra("Progress", progress);
sendBroadcast(i);
}
}
Then to start downloading a file, simply do:
Intent i = new Intent(context, FileDownloader.class);
i.putExtra("Path", folderpath);
i.putExtra("Filename", filename);
i.putExtra("CallbackString",
"progress_callback");
startService(i);
Now you should handle the "progress_callback" callback as you would with any other broadcasts, registering the receiver etc. In this example, using the filepath to determine which file should have it's progress visual updated.
Do not forget to register the service in your manifest.
<service android:name="yourpackage.FileDownloader" />
Note:
With this solution you can start a service for each file immediately and casually handle incoming broadcasts as each service reports new progress. No need to wait for each file to be downloaded before starting the next. But if you insist on downloading the files in serial, you can of course, by waiting for 100% progress callbacks before invoking the next.
Using 'CallbackString'
You can use it like this in your Activity:
private BroadcastReceiver receiver;
@Overrride
public void onCreate(Bundle savedInstanceState){
// your oncreate code
// starting the download service
Intent i = new Intent(context, FileDownloader.class);
i.putExtra("Path", folderpath);
i.putExtra("Filename", filename);
i.putExtra("CallbackString",
"progress_callback");
startService(i);
// register a receiver for callbacks
IntentFilter filter = new IntentFilter("progress_callback");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
Bundle b = intent.getExtras();
String filepath = b.getString("Filepath");
int progress = b.getInt("Progress");
// could be used to update a progress bar or show info somewhere in the Activity
}
}
registerReceiver(receiver, filter);
}
Remember to run this in the onDestroy
method:
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
Note that "progress_callback" could be any other String of your choice.
Example code borrowed from Programmatically register a broadcast receiver