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

Oma*_*mar 5 java service android download

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

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

}
Run Code Online (Sandbox Code Playgroud)

主要活动的代码:

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

谢谢.

Com*_*are 9

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

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

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

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

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

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

这将是一个解决方案.一个变化就是让服务发送一个有序的广播,如果它仍然在屏幕上或由BroadcastReceiver那个会做的话,你的活动将被选中Notification.这是一篇博文,其中有更多内容,这是一个展示这个概念的小样本应用程序.