我有两个 Intent 服务 - IntentServiceA
和 IntentServiceB
它们具有以下类定义:
public class FirstService extends IntentService {
public FirstService() {
super("first_service");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("chi6rag", "first starts");
for (long i = 0l; i < 10000000l; i++) {
if (i == 0l) Log.d("chi6rag", "first started");
}
Log.d("chi6rag", "first ends");
}
}
和
public class SecondService extends IntentService {
public SecondService() {
super("second_service");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("chi6rag", "second starts");
for (long i = 0l; i < 10000000l; i++) {
if (i == 0l) Log.d("chi6rag", "second started");
}
Log.d("chi6rag", "second ends");
}
}
如果我在我的 Activity 中执行以下代码:
startService(新的 Intent (this, IntentServiceA.class));
startService(new Intent(this, IntentServiceB.class));
我在日志中看到以下内容:
D/chi6rag (11734):首先启动
D/chi6rag (11734): 第一次启动
D/chi6rag (11734):第二次启动
D/chi6rag (11734):第二次启动
D/chi6rag (11734):第一次结束
D/chi6rag (11734):第二个结束
虽然如果有人看到 Intent Service Docs,它清楚地提到它将 一次一个 Intent
传递给 IntentService 的 onHandleIntent
方法
问题:每个 Intent 服务是否都有单独的工作线程?因为预期的日志是:
D/chi6rag (11734):首先启动
D/chi6rag (11734): 第一次启动
D/chi6rag (11734):第一次结束
D/chi6rag (11734):第二次启动
D/chi6rag (11734):第二次启动
D/chi6rag (11734):第二个结束
最佳答案
IntentService 执行以下操作:
- Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
- Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about
multi-threading- Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.
由于您有多个类扩展形式 IntentService,每个类都有自己特定的 onHandleIntent。这些在单独的工作队列中处理。
关于android - 不同的 Intent 服务是否在同一线程上排队?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37429107/