gpt4 book ai didi

android - IntentService 和线程池

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:50:57 24 4
gpt4 key购买 nike

我有一个 IntentService,它应该像管理器一样工作,并在提交到线程池的队列(可运行)中创建任务。

我对 IntentService 的生命周期有点困惑:

protected abstract void onHandleIntent (Intent intent) 方法已经在单独的线程上运行。在 onHandleIntent 中,我将创建一个新的 Runnable 实例并将其提交给 ThreadPool。我的服务如下所示:

    public class SyncService extends IntentService {

private final ThreadPoolExecutor threadPool;

public SyncService() {
super("SyncService");
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
threadPool = new ThreadPoolExecutor(1, 1, 20, TimeUnit.SECONDS, queue);
}

@Override
public void onCreate() {
super.onCreate();
EventBus.getInstance().register(this);
}

@Override
public void onDestroy() {
super.onDestroy();
EventBus.getInstance().unregister(this);
}

@Override
protected void onHandleIntent(Intent intent) {

if (intent.getAction().equals("sync")){
threadPool.submit(new SyncRunnable());
}else
if(intent.getAction().equals("delete")){
threadPool.submit(new DeleteRunnable());
} else
if(intent.getAction().equals("register")){
threadPool.submit(new RegisterRunnable())
}

}
}

我的问题:

  1. 在 IntentService 中使用 ThreadPool 是个好主意吗?
  2. 如果我使用 ThreadPool,那么如果 Threadpool 没有更多的 Runnables 可以执行或排队,那么 IntentService 将被销毁,对吗?
  3. IntentService 已经是我想要实现的东西了吗?我是否应该简单地在onHandleIntent() 因为这个方法已经运行在IntentService 工作线程?如果是,是否有队列限制intent,因为 onHandleIntent() 最多可以提前 30 秒运行完成并处理下一个 Intent。

最佳答案

Is it a good idea to use a ThreadPool in a IntentService?

不是真的。 IntentService 已经是您尝试实现的单线程(串行)变体。我会直接从 Service 派生。

If I use a ThreadPool, than the IntentService will be destroyed if the Threadpool has no more Runnables to execute or queued, right?

没有。一旦您从 onHandleIntent 返回,IntentService 就可以进入销毁状态 - 即立即,因为 threadPool.submit 是非阻塞的。 source内它使用服务启动时获得的 startId 调用 stopSelf(int)

private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}

如果您使用最新(最高)的 startId 调用 stopSelfService 将进入销毁状态。如果队列中有更新的开始,它将继续运行。

如果服务进入销毁状态,它不会杀死你的线程池,因为它不知道它。问题是 Android 现在认为你的服务已经死了,它不再算作保留你的应用程序进程的理由。服务运行状态与销毁状态本质上只是一种告诉 Android 正在发生某些事情并且您不想被销毁的方式。

如果您想以正确的方式做到这一点,您必须使服务状态与实际发生的事情保持同步。

Is IntentService already something that I want to achieve and should I simply execute my (long running) Runnable code in the onHandleIntent() because this method alread runs on the IntentService worker Thread?

如果您对单线程串行执行感到满意,是的。这就是 onHandleIntent 为您所做的。

If yes, is there a queue limit for intent, since onHandleIntent() could run up to 30 seconds before finishing and handling the next Intent.

没有限制(据我所知这是一个链表)。但是也没有什么可以阻止您产生超出其处理能力的任务,这最终会导致某种溢出。

关于android - IntentService 和线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20402650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com