Unexpected behavior of IntentService

Posted by kknight on Stack Overflow See other posts from Stack Overflow or by kknight
Published on 2010-05-05T22:14:29Z Indexed on 2010/05/05 22:18 UTC
Read the original article Hit count: 409

Filed under:

I used IntentService in my code instead of Service because IntentService creates a thread for me in onHandleIntent(Intent intent), so I don't have to create a Thead myself in the code of my service.

I expected that two intents to the same IntentSerivce will execute in parallel because a thread is generated in IntentService for each invent. But my code turned out that the two intents executed in sequential way.

This is my IntentService code:

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.");
        }
    }
}

And the code call the service is below:

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);

    }
}

I saw this log message in the log:

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

The log shows that the second intent waited the first intent to finish and they are in the same thread.

It there anything I misunderstood of IntentService. To make two service intents execute in parallel, do I have to replace IntentService with service and start a thread myself in the service code?

Thanks.

© Stack Overflow or respective owner

Related posts about android