澄清 IntentService 的内部运作
Clarification on inner workings of IntentService
我试图理解 IntentService
中的特定逻辑,特别是 ServiceHandler
:
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);
}
}
据我所知,stopSelf()
被多次调用 - 每个 startService
调用一次。如果有多个项目要处理,stopSelf
不会中断待处理项目的流程吗?显然这不是正在发生的事情,因为 IntentService
实际上有效,但为什么呢?似乎 stopSelf
应该在处理完所有 Intent
之后调用。
另一个问题 - 在 onCreate
中创建的 HandlerThread
何时真正停止?显然它没有被 stopSelf
?
停止
stopSelf(int startId)
方法只会停止 Service
如果最近一次启动是 startId
。如果 IntentService
在它仍在处理 Intent
时再次启动,则会向它传递一个不同的 startId
,因此使用之前的 startId
调用 stopSelf()
将不会停止它。
在 onCreate()
中开始的 HandlerThread
将在 Service
实例结束时结束,因为它的 Looper
在 IntentService
的 onDestroy()
方法。
stopSelf(int) calls stopSelfResult(int) 表示:
Stop the service if the most recent time it was started was startId
. This is the same as calling stopService(Intent)
for this particular service but allows you to safely avoid stopping if there is a start request from a client that you haven't yet seen in onStart(Intent, int)
.
由于 IntentService
只按顺序工作,直到最后一个 startId
发送到 stopSelf
才会真正停止
我试图理解 IntentService
中的特定逻辑,特别是 ServiceHandler
:
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);
}
}
据我所知,stopSelf()
被多次调用 - 每个 startService
调用一次。如果有多个项目要处理,stopSelf
不会中断待处理项目的流程吗?显然这不是正在发生的事情,因为 IntentService
实际上有效,但为什么呢?似乎 stopSelf
应该在处理完所有 Intent
之后调用。
另一个问题 - 在 onCreate
中创建的 HandlerThread
何时真正停止?显然它没有被 stopSelf
?
stopSelf(int startId)
方法只会停止 Service
如果最近一次启动是 startId
。如果 IntentService
在它仍在处理 Intent
时再次启动,则会向它传递一个不同的 startId
,因此使用之前的 startId
调用 stopSelf()
将不会停止它。
在 onCreate()
中开始的 HandlerThread
将在 Service
实例结束时结束,因为它的 Looper
在 IntentService
的 onDestroy()
方法。
stopSelf(int) calls stopSelfResult(int) 表示:
Stop the service if the most recent time it was started was
startId
. This is the same as callingstopService(Intent)
for this particular service but allows you to safely avoid stopping if there is a start request from a client that you haven't yet seen inonStart(Intent, int)
.
由于 IntentService
只按顺序工作,直到最后一个 startId
发送到 stopSelf