简体   繁体   English

如何在Android中使用intentservice同时下载多个文件?

[英]How to download multiple files concurrently using intentservice in Android?

I want to create a service similar to this one, (reference from Here ), to download multiple files asynchronously in Android. 我想创建一个类似于这个的服务(从这里引用),以便在Android中异步下载多个文件。

public static class DownloadingService extends IntentService {
public static String PROGRESS_UPDATE_ACTION = DownloadingService.class
        .getName() + ".newDownloadTask";
private ExecutorService mExec;
private CompletionService<NoResultType> mEcs;
private LocalBroadcastManager mBroadcastManager;
private List<DownloadTask> mTasks;

public DownloadingService() {
    super("DownloadingService");
    mExec = Executors.newFixedThreadPool( 3 ); // The reason to use multiple thread is to download files asynchronously. 
    mEcs = new ExecutorCompletionService<NoResultType>(mExec);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}

@Override
protected void onHandleIntent(Intent intent) {

  while(true)
  {
    if( cursor <= totalDownloadQueue.size() -1) {   //totalDownloadQueue is a static ArrayList which contains numerous DownloadTask
        mEcs.submit(totalDownloadQueue.get(cursor)); 
        cursor++; // The variable cursor is also a static int variable. 
    }
  }// continuously observing the totalDownloadQueue. If any download item is added. Then the thread are dispatched to handle that.
    mExec.shutdown();
}

The user can select download items among listview in different fragments. 用户可以在不同的片段中选择listview中的下载项。 My strategy is that as the user select the items and press download button, these items are passed into DownloadTask which is responsible for downloading a file. 我的策略是,当用户选择项目并按下载按钮时,这些项目将被传递到负责下载文件的DownloadTask中。 Then the download tasks are added into the totalDownloadQueue . 然后将下载任务添加到totalDownloadQueue

Here are some questions: 以下是一些问题:

  1. I know the intentservice is triggered by some defined action. 我知道intentservice是由一些定义的动作触发的。 But what I want to is to create a background service watching the totalDownloadQueue , if any new downloadtask is availabe, then some thread are called to operate the tasks. 但我想要的是创建一个观看totalDownloadQueue的后台服务,如果有任何新的downloadtask任务totalDownloadQueue ,则调用一些线程来操作任务。

    What's the side effect if I did so for this customized intentservice ? 如果我为这个定制的intentservice这样做intentservice什么intentservice

    What alternative class should I use? 我应该使用哪种替代课程? Please provide sample code along with the explanation, thanks. 请提供sample code以及解释,谢谢。

  2. As I know, the initialization of the threads is only called by once. 据我所知,线程的初始化只被调用一次。 If I start the service at the beginning of the application and the threads should be killed as the user terminate the app.(I mean when he swipe out the window.) Do the threads exist after the user exit the application? 如果我在应用程序开始时启动服务,并且应该在用户终止应用程序时终止线程。(我的意思是当他swipe out窗口时。)用户退出应用程序后是否存在线程?

  3. If this approach still can't resolve the issue about downloading files asynchronously? 如果这种方法仍然无法解决异步下载文件的问题? What other strategy should I adopt? 我应该采取什么其他策略? Please provide some example code or reference so that I can modify on it. 请提供一些示例代码或参考,以便我可以对其进行修改。

I have spent 7 days dealing with the complex requirement, any help please! 我花了7天时间处理复杂的要求,请帮忙!

to download multiple files asynchronously in Android. 在Android中异步下载多个文件。

and also i think you want to download simultaneously. 而且我认为你想同时下载。

i think you misused the intentservice . 我认为你误用了intentservice intentservice has a looper and a handler and each call to start causes to create a message for the handler. intentservice有一个looper和一个handler ,每次启动调用都会导致为处理程序创建一个消息。 all messages are queued in the looper queue and are served one at a time. 所有消息都在looper queue中排队,并一次提供一个。

you should use normal service and do not use intentservice because you want to download simultaneously not one at a time. 你应该使用普通服务,不要使用intentservice因为你想同时下载一个而不是一个。 extend service class and in onCreate method you can create multiple threads and each thread can take a messages from onStartCommand . 扩展服务类,在onCreate方法中,您可以创建多个线程,每个线程都可以从onStartCommand获取消息。 i do not want to copy and paste the doc example because i think it is better to read all of the doc again. 我不想复制和粘贴文档示例,因为我认为最好再次阅读所有文档。 if you read it you can completely understand how to create service that handles multiple task simultaneously although it has created just one thread in the example. 如果您阅读它,您可以完全理解如何创建同时处理多个任务的服务,尽管它在示例中只创建了一个线程。

http://developer.android.com/guide/components/services.html http://developer.android.com/guide/components/services.html

what I want to is to create a background service watching the totalDownloadQueue 我想要的是创建一个观看totalDownloadQueue的后台服务

i think you do not need that. 我想你不需要那个。 just when you create downloadtask call service, your message is delivered to service class and in that class you can create blockingqueue to handle your messages by threads . 就在您创建downloadtask调用服务时,您的message将传递到服务类,在该类中,您可以创建blockingqueue来按threads处理您的消息。

Do the threads exist after the user exit the application? 用户退出应用程序后是否存在线程?

yes and maybe no. 是的,也许不是。 it depends on the process, if the process exists yes but if the process has been destroyed no. 它取决于进程,如果进程存在肯定但是进程已被销毁否。 again read lifecycle of process to understand what process is killed or kept by android. 再次读取进程的lifecycle ,以了解android被杀死或保留的进程。

http://developer.android.com/guide/components/processes-and-threads.html http://developer.android.com/guide/components/processes-and-threads.html

if this approach still can't resolve the issue about downloading files asynchronously? 如果这种方法仍然无法解决异步下载文件的问题? What other strategy should I adopt? 我应该采取什么其他策略? Please provide some example code or reference so that I can modify on it. 请提供一些示例代码或参考,以便我可以对其进行修改。

you can use downloadmanager but it downloads sequentially. 你可以使用downloadmanager但它会顺序下载。

http://developer.android.com/reference/android/app/DownloadManager.html http://developer.android.com/reference/android/app/DownloadManager.html

http://blog.vogella.com/2011/06/14/android-downloadmanager-example/ http://blog.vogella.com/2011/06/14/android-downloadmanager-example/

IntenService and AsyncTask provide a single worker thread, therefore simultaneous download of multiple images is not possible. IntenServiceAsyncTask提供单个工作线程,因此无法同时下载多个图像。 However, i strongly suggest ThreadPoolExecutor for your requirements. 但是,我强烈建议ThreadPoolExecutor满足您的要求。 It basically creates a pool of threads which are expended/shrink based on the number of tasks you apply or number of files you want to download. 它基本上创建了一个线程池,根据您应用的任务数量或要下载的文件数量来扩展/收缩。 THreadPoolExecutor handles practically every aspect of threads management and its quite efficient. THreadPoolExecutor处理线程管理的每个方面,并且非常有效。 You create a single executor with the as in this code sample: 使用此代码示例中的as创建单个执行程序:

ExecutorService tpExecutor=
        new ThreadPoolExecutor(
                coreSize,      // the basic number of threads, when a task is added to the queue
                               // a new thread is created if nrOfThreads < coreSize  
                maxPoolSize,   // maximum number of threads created
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>()
                ); 

You can submit multiple downloading task by executing runnables: 您可以通过执行runnables提交多个下载任务:

tpExecutor.execute(new Runnable());

From the sound of it you might benefit from using the onProgressUpdate method from ASyncTask , which can keep you updated on progress. 从它的声音中你可以从ASyncTask使用onProgressUpdate方法中受益 ,它可以让你随时了解最新进展。 Maybe have a read through the class description -- it sounds like just what you need. 也许通过课程描述阅读 - 听起来就像你需要的那样。 It also comes with lots of sample code! 它还附带了大量的示例代码!

Hope I am of help! 希望我有所帮助!

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

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