Reputation: 8145
My application has a lot of optional data that can be downloaded so I decided to use a Service to handle all the downloads in the background, So I started learning it and here is where i got:
public class DownloadService extends IntentService{
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String URL=intent.getStringExtra("DownloadService_URL");
String FileName=intent.getStringExtra("DownloadService_FILENAME");
String Path=intent.getStringExtra("DownloadService_PATH");
try{
URL url = new URL(URL);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Path+FileName);
byte data[] = new byte[1024];
int count = 0;
while ((count = input.read(data)) != -1) {
output.write(data);
}
output.flush();
output.close();
input.close();
}
catch(Exception e){ }
}
}
The code from the main activity:
Intent ServiceIntent = new Intent(this,DownloadService.class);
ServiceIntent.putExtra("DownloadService_URL", "the url...");
ServiceIntent.putExtra("DownloadService_FILENAME", "Test1.rar");
ServiceIntent.putExtra("DownloadService_PATH", "/sdcard/test/");
startService(ServiceIntent);
Thanks.
Upvotes: 5
Views: 7761
Reputation: 1006614
Is the code used to download the files correct?
I don't like the use of concatenation to create fully-qualified file paths (use the appropriate File
constructor). Catching exceptions and not doing anything with them is a really bad idea. On Android 2.3 and higher, you should consider using DownloadManager
.
Otherwise, it's probably OK for basic stuff.
I want to download a lot of files.. So should I startService for each different URL?
That should work fine. Note that they will be downloaded one at a time, as IntentService
has only one background thread.
I would like to inform the user of the percentage done.. But the Service doesnt have a UI. Should I do that in the notification bar?
That would be one solution. A variation on that would be to have the service send an ordered broadcast, to be picked up by your activity if it is still on-screen or by a BroadcastReceiver
that would do the Notification
. Here is a blog post with more on that, and here is a tiny sample application demonstrating the concept.
Upvotes: 9