【问题标题】:How do download managers work on Android?下载管理器如何在 Android 上运行?
【发布时间】:2014-07-30 01:52:19
【问题描述】:

我想知道下载管理器(not the DownloadManager class introduced in API 9)的机制,在我目前的项目中,我需要实现一些与下载管理器相同的东西。

我的基本理解是它使用 Service 来下载文件。但我无法理解的是它将如何处理多文件下载请求,e.g.当前正在下载文件。现在用户添加了另一个要下载的文件。我认为单个服务无法处理它。它可以?还是有其他方法可以做到这一点?有什么建议吗?

如果问题不够清楚,请原谅我,因为我自己也不太清楚我的疑问。 :(

【问题讨论】:

    标签: java android service


    【解决方案1】:

    他们使用的是多线程套筒轮。

    意味着,有一个 ForegroundService 处理服务中的不同线程。

    ForegroundService 确保它保持活动状态。线程本身是在后台线程中运行的单个进程。

    有几个可用的 ThreadExecutor 可确保您只有几个线程并行运行或逐个线程处理它们。

    这是一个制作 SocketWheel 的好教程http://www.javaspecialists.eu/archive/Issue023.html

    来源:

    线程执行器http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html

    ThreadPoolExecutorExectuorService vs ThreadPoolExecutor (which is using LinkedBlockingQueue)

    前台服务Android - implementing startForeground for a service?

    已编辑:一些代码

    public class DLService extends Service {
    
    @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
      Notification note=new Notification(R.drawable.somegraphics, "some title", randomnr);
      Intent i=new Intent(this, ActivityClassToOpenWhenClicked.class);
      i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
      PendingIntent pi=PendingIntent.getActivity(this, 0, i, 0);
      note.setLatestEventInfo(this, "downloadmanager","downloading.. nothing", pi);
      note.flags|=Notification.FLAG_NO_CLEAR;
      startForeground(1337, note); 
     // if (intent.hasExtra("dlurl")) { 
        new Thread(new Runnable() {
             public void run() {
            new Client("http://yourfile.com/file.jpg");     
         }
        }).start();
      return START_NOT_STICKY;
     }
    
    class Client {
      public Client(String filetodownload) throws Exception {
      //do your http connection. for example one download  #
      // HttpUrlConnection httpConnection = new .....
     }
    }
    }
    

    这只是一个快速编码示例,未经测试。但它显示了这个概念。 服务本身接受一个 Intent,它可以是文件所在的 url。然后它创建一个新的线程来完成这项工作。只要下载文件,线程就会运行。 foregroundService 确保服务将保持活动状态。您还可以创建一个 ThreadPoolExecutor,它在 onec 上处理多个线程。阅读http://developer.android.com/training/multiple-threads/create-threadpool.html 获取说明。

    【讨论】:

    • 我认为你没有仔细阅读我的答案 :-) 是的,一个单一的服务可以处理这个问题。创建了一个服务,服务本身创建了几个线程,这些线程创建了一个套接字(或 HTTPConnection)。线程本身可以通过发送 Intent Extras 或使用 Listeners 与 Service 进行通信。
    • 对不起!我没有阅读您编辑的答案,并根据以前的来源发表了评论,这对我来说并不清楚。所以基本上我需要在服务中实现 ThreadPoolExecutor 来完成我的工作?
    • 我会发布一些伪代码,等等... :-)
    • 这将有很大帮助! :)
    • 已更新。它只是伪代码。不要让它工作,但它会告诉你如何做到这一点。
    猜你喜欢
    • 2011-03-30
    • 2011-11-29
    • 2014-02-28
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2012-04-14
    相关资源
    最近更新 更多