0

在 IntentService 中,我使用的是 ThreadPoolExecutor poolSize 8 和 maxPoolSize 10。无论何时启动 Service,都会影响 UI。在 runTask() 方法中,我将任务添加到线程池。

private ThreadPoolExecutor threadPool = null;
private final LinkedBlockingQueue<Runnable> threadsQueue =
  new LinkedBlockingQueue<Runnable>();
private Collection<Future<?>> futures = new LinkedList<Future<?>>();

public MyService(String name) {
 super(name);
 threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime,
     TimeUnit.SECONDS, threadsQueue);
}

public void runTask(Runnable task) {
  futures.add(threadPool.submit(task));
}

/**
* When ever we call this method it will hold the main thread untill the tasks
* in thread pool are completed.
*/

public void waitForThreadPool() {
 for (Future<?> future : futures) {
   try {
     future.get();
   } catch (InterruptedException e) {
     e.printStackTrace();
   } catch (ExecutionException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
}
4

1 回答 1

1

我建议在服务中创建一个单独的线程(服务在 UI 线程中运行),它将等待执行程序完成。我就是这样做的

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{

    // check what you have to here
    // ...

    if (state == State.IDLE) {
        state = State.IN_PROGRESS;

        new Thread()
        {
            @Override
            public void run()
            {
                performAndWait();
                stopSelf();
            }
        }.start();
    }

}

private void performAndWait() {

    //add tasks to ExecutorService

    for (String key : this.data.keySet()) {
        final Job pending = new Job(this.context, key, this.data.get(key));
        try {
            this.service.submit(pending);
        } catch (RejectedExecutionException e) {
            // all rejected stuff go here for the next attempt when all finishes
            this.rejected.add(pending);
        }
    }

    // wait

    service.shutdown();
    try {
        service.awaitTermination(3600, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
于 2013-05-21T11:39:50.783 回答