在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();
}
}
}
答案 0 :(得分: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();
}
}