Tôi đã sử dụng IntentService trong mã của tôi thay vì Dịch vụ vì IntentService tạo chuỗi cho tôi trong onHandleIntent (Intent intent), vì vậy tôi không phải tự tạo Thead trong mã dịch vụ của mình.Hành vi không mong muốn của IntentService
Tôi dự kiến rằng hai ý định vào cùng IntentSerivce sẽ thực hiện song song vì một luồng được tạo trong IntentService cho mỗi phát minh. Nhưng mã của tôi bật ra rằng hai ý định được thực hiện theo cách tuần tự.
Đây là mã IntentService tôi:
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.");
}
}
}
Và cuộc gọi mã dịch vụ là bên dưới:
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);
}
}
tôi thấy thông tin đăng nhập này trong nhật ký:
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
Các nhật ký cho thấy ý định thứ hai chờ ý định đầu tiên kết thúc và chúng nằm trong cùng một luồng.
Có bất kỳ điều gì tôi hiểu sai về IntentService. Để thực hiện hai mục đích dịch vụ thực thi song song, tôi có phải thay thế IntentService bằng dịch vụ và tự khởi chạy một luồng trong mã dịch vụ không?
Cảm ơn.
Mẫu thiết kế của IntentService là hàng đợi công việc đảm bảo rằng các yêu cầu được xếp hàng đợi và không được xử lý song song. Như đã chỉ ra dưới đây, bạn có thể kích hoạt AsyncTask cho mỗi công việc song song. Hãy chắc chắn rằng mã dịch vụ của bạn là reentrant. – mobibob