【发布时间】:2014-10-28 20:37:39
【问题描述】:
我想创建一个与此类似的服务(参考来自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 天时间处理复杂的需求,请大家帮忙!
【问题讨论】:
标签: java android multithreading android-download-manager android-intentservice