IntentService中的ExecutorService。它会被Android杀死吗?

时间:2015-01-03 17:46:05

标签: java android multithreading intentservice

我写了一个IntentService,我将用它从网上下载一些重量数据(主要是大图)。

该课程如下:

public class UpdateService extends IntentService {

    public UpdateService() {
        super(UpdateService.class.getCanonicalName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        final ExecutorService executorService = Executors.newFixedThreadPool(3);
        List<ListenableFuture> futures = new ArrayList<>();

        for(Runnable r : getRunnables()){
            executorService.execute(r);
            futures.add(r.getFuture());
        }

        Futures.addCallback(

                Futures.allAsList( futures ),

                new FutureCallback<List<Boolean>>() {
                    @Override
                    public void onSuccess(List<Boolean> result) {
                        // do some logic here
                        executorService.shutdown();
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        // do some error handling here
                        executorService.shutdown();
                    }
                }
        );      

    }
}

正如您所看到的,onHandleIntent()方法返回的速度非常快,因为大部分活动都是在ExecutorService执行的 Runnables 中执行的。

在一段时间后返回ExecutorService方法后,android会杀死IntentService并因此终止onHandleIntent()启动的线程吗?

或者以某种方式检测线程是否仍然存在且意图服务仍然存在?

万一,如何更改代码以防止Android终止服务?

1 个答案:

答案 0 :(得分:5)

  

android会杀死IntentService吗

IntentService将通过stopSelf()自行销毁。

  

并因此在一段时间后终止ExecutorService启动的线程

线程被泄露,但它们将运行,直到进程终止。由于您不再告诉Android Service您的流程正在运行,您的流程可能会很快终止。

  

如何更改代码以防止Android终止服务?

请勿使用IntentService。使用Service,并在所有线程完成工作后自己致电stopSelf()

相关问题