如何在服务和应用程序android多任务处理

时间:2014-07-12 14:47:35

标签: android service multitasking

我在我的服务中有一个文件下载服务我有一个Asynctask做下行,我正在使用内容提供程序来保存文件状态。我的问题是当asynctask运行任何其他asynctask不能在app中运行所有他们等到下载任务完成。想法?

2 个答案:

答案 0 :(得分:1)

所有AsyncTasks后台工作都在后台工作线程中串行运行,旨在解决短期问题。

由于您可能正在使用长时间运行的连接,因此您应该在单独的Service内的Thread上执行此操作。一个简单的方法是通过Intent接收连接参数并直接在startCommand()上启动一个新线程。

答案 1 :(得分:1)

从蜂窝版开始,AsynchTasks在串行执行器中运行。因此,如果您计划并行运行许多下载作业,那么您需要做的是在Asynchtask中使用ExecutorService来并行执行作业。

您也可以在创建AsynchTask时将执行器类型设置为并行而不是顺序,但我不建议这样做。

以下是一些使用Loader的代码片段:

private ExecutorService executorService;

private static final int MAX_RUNNABLE_THREADS = 800;
private static final int KEEP_ALIVE_TIME = 6;


//in constructor and probably in onStartLoading...
if(this.isNetworkfast){
    this.executorService = new ThreadPoolExecutor(0, MAX_RUNNABLE_THREADS
                                                        , KEEP_ALIVE_TIME
                                                        , TimeUnit.SECONDS
                                                        , new SynchronousQueue<Runnable>()
                                                );
}else {
    this.executorService = Executors.newFixedThreadPool(3);
}


//in onReset
this.executorService.shutdownNow();
try {
    if (executorService.awaitTermination(20, TimeUnit.SECONDS)) {
        Log.i(TAG, "executorService shutdown completed.");
    }else{
        Log.e(TAG, "executorService shutdown failed to finish completely.");
        if(this.isErrorReportingEnabled){
            this.errorMap.put("error_" + (++errorCount), "executorService shutdown failed to finish completely.");
        }
    }
} catch (InterruptedException e) {
    Log.e(TAG, "DownloadNseQuotesAsynchTaskLoader executorService shutdown interrupted.");
    if(this.isErrorReportingEnabled){
        this.errorReporter.reportCustomMessagesWithException("exception_" + (++errorCount)
                                    , "DownloadNseQuotesAsynchTaskLoader executorService shutdown interrupted.", e);
    }
}


//in loadInBackground....
//do your processing to determine the number of workers/runnables needed and based on that
final CountDownLatch latch = new CountDownLatch(number of workers);

MyWorker worker = new MyWorker(latch, data set....); 

this.executorService.execute(worker);

//and later in the same method we wait on the latch for all workers to finish
try {
    latch.await(); //blocks the current thread until the latch count is zero
    //all Workers have finished, now read in the processed data if you want
    for (MyWorker worker : workers) {
        SomeDataVO dataVO = worker.getData();
        .......
    }
} catch (InterruptedException ie) {
    Log.e(TAG, "Interrupted exceltion while await on CountDownLatch running", ie);
    if(this.isErrorReportingEnabled){
        this.errorReporter.reportCustomMessagesWithException("exception_" + (++errorCount)
                                        , "Interrupted exception while await on CountDownLatch running", ie);
    }
}

这不是完整的部分,但应足以为您提供有关如何使用它的想法。