繁体   English   中英

使用android中的服务下载多个文件

[英]Download multiple files using a Service in android

我的应用程序有很多可以下载的可选数据,所以我决定使用一个服务来处理后台的所有下载,所以我开始学习它,这里是我得到的:

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){ }
    }

}

主要活动的代码:

        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);
  1. 用于下载文件的代码是否正确? 我正确使用本服务吗?
  2. 我想下载很多文件..那么我应该为每个不同的URL启动服务吗?
  3. 我想通知用户完成的百分比..但服务没有UI。 我应该在通知栏中这样做吗?

谢谢。

用于下载文件的代码是否正确?

我不喜欢使用连接来创建完全限定的文件路径(使用适当的File构造函数)。 捕捉异常并且不对它们做任何事情是一个非常糟糕的主意。 在Android 2.3及更高版本中,您应该考虑使用DownloadManager

否则,基本的东西可能就好了。

我想下载很多文件..那么我应该为每个不同的URL启动服务吗?

这应该工作正常。 请注意,它们将一次下载一个,因为IntentService只有一个后台线程。

我想通知用户完成的百分比..但服务没有UI。 我应该在通知栏中这样做吗?

这将是一个解决方案。 对此的一种变体是让服务发送有序广播,如果它仍在屏幕上,则由您的活动接收,或者由发出NotificationBroadcastReceiver 这是一篇博文,其中有更多内容, 这是一个展示这个概念的小样本应用程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM