[英]Download multiple files using a Service in android
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. 谢谢。
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). 我不喜欢使用连接来创建完全限定的文件路径(使用适当的
File
构造函数)。 Catching exceptions and not doing anything with them is a really bad idea. 捕捉异常并且不对它们做任何事情是一个非常糟糕的主意。 On Android 2.3 and higher, you should consider using
DownloadManager
. 在Android 2.3及更高版本中,您应该考虑使用
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?
我想下载很多文件..那么我应该为每个不同的URL启动服务吗?
That should work fine. 这应该工作正常。 Note that they will be downloaded one at a time, as
IntentService
has only one background thread. 请注意,它们将一次下载一个,因为
IntentService
只有一个后台线程。
I would like to inform the user of the percentage done.. But the Service doesnt have a UI.
我想通知用户完成的百分比..但服务没有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
. 对此的一种变体是让服务发送有序广播,如果它仍在屏幕上,则由您的活动接收,或者由发出
Notification
的BroadcastReceiver
。 Here is a blog post with more on that, and here is a tiny sample application demonstrating the concept. 这是一篇博文,其中有更多内容, 这是一个展示这个概念的小样本应用程序 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.