我想创建一个与此类似的服务(参考来自Here),以在 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();
}
用户可以listview
在不同的片段中选择下载项目。我的策略是,当用户选择项目并按下下载按钮时,这些项目被传递到DownloadTask
负责下载文件的项目中。然后将下载任务添加到totalDownloadQueue
.
这里有一些问题:
我知道这
intentservice
是由一些定义的动作触发的。但我想要的是创建一个后台服务来观察totalDownloadQueue
,如果有任何新downloadtask
的可用,那么就会调用一些线程来操作任务。如果我为这个定制这样做有什么副作用
intentservice
?我应该使用什么替代课程?请提供
sample code
说明,谢谢。据我所知,线程的初始化只被调用一次。如果我在应用程序开始时启动服务并且线程应该在用户终止应用程序时被终止。(我
swipe out
的意思是当他窗口时。)用户退出应用程序后线程是否存在?如果这种方法仍然无法解决异步下载文件的问题?我应该采取什么其他策略?请提供一些示例代码或参考,以便我可以对其进行修改。
我花了 7 天时间处理复杂的需求,请大家帮忙!