【发布时间】:2010-05-05 22:14:29
【问题描述】:
我在我的代码中使用了 IntentService 而不是 Service,因为 IntentService 在 onHandleIntent(Intent intent) 中为我创建了一个线程,所以我不必在我的服务代码中自己创建一个 Thead。
我预计同一个 IntentSerivce 的两个意图将并行执行,因为在 IntentService 中为每个 invent 生成一个线程。但我的代码证明这两个意图是按顺序执行的。
这是我的 IntentService 代码:
public class UpdateService extends IntentService {
public static final String TAG = "HelloTestIntentService";
public UpdateService() {
super("News UpdateService");
}
protected void onHandleIntent(Intent intent) {
String userAction = intent
.getStringExtra("userAction");
Log.v(TAG, "" + new Date() + ", In onHandleIntent for userAction = " + userAction + ", thread id = " + Thread.currentThread().getId());
if ("1".equals(userAction)) {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
Log.e(TAG, "error", e);
}
Log.v(TAG, "" + new Date() + ", This thread is waked up.");
}
}
}
调用服务的代码如下:
public class HelloTest extends Activity {
//@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent selectIntent = new Intent(this, UpdateService.class);
selectIntent.putExtra("userAction",
"1");
this.startService(selectIntent);
selectIntent = new Intent(this, UpdateService.class);
selectIntent.putExtra("userAction",
"2");
this.startService(selectIntent);
}
}
我在日志中看到了这条日志消息:
V/HelloTestIntentService( 848): Wed May 05 14:59:37 PDT 2010, In onHandleIntent for userAction = 1, thread id = 8
D/dalvikvm( 609): GC freed 941 objects / 55672 bytes in 99ms
V/HelloTestIntentService( 848): Wed May 05 15:00:00 PDT 2010, This thread is waked up.
V/HelloTestIntentService( 848): Wed May 05 15:00:00 PDT 2010, In onHandleIntent for userAction = 2, thread id = 8
I/ActivityManager( 568): Stopping service: com.example.android/.UpdateService
日志显示第二个意图等待第一个意图完成并且它们在同一个线程中。
我对 IntentService 有什么误解。要让两个服务意图并行执行,是否必须将 IntentService 替换为服务并在服务代码中自己启动一个线程?
谢谢。
【问题讨论】:
标签: android