【问题标题】:Download multiple files using a Service in android在android中使用服务下载多个文件
【发布时间】:2011-08-27 15:20:15
【问题描述】:

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

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。我应该在通知栏中这样做吗?

谢谢。

【问题讨论】:

    标签: java android service download


    【解决方案1】:

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

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

    否则,基本的东西可能没问题。

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

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

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

    这将是一种解决方案。一个变体是让服务发送一个有序的广播,如果它仍然在屏幕上,或者由BroadcastReceiver 执行Notification,则由您的活动接收。 Here is a blog post 提供更多信息,here is a tiny sample application 展示了这个概念。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      相关资源
      最近更新 更多