tags:

views:

31

answers:

1

I just wonder whether there will be any conflict if two service intents are sent to the same service at the same time. My code is as below:

public static class UpdateService extends Service {

    @Override
    public void onStart(Intent intent, int startId) {
        int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);

        UpdateThread updateThread = new UpdateThread();
        updateThread.mWidgetId = widgetId;
        updateThread.mContext = this;

        updateThread.start();

        stopSelf();
    }
}

Suppose there are two intents, intent 1 and intent 2, for UpdateService at the same time. As I understand, there will be only one UpdateService instance. Then, will the two intents cause the service code to run sequentially like the workflow below?

  1. UpdateService starts, i.e. onStart() is called, for intent 1.
  2. UpdateService stops because stopSelf() is called in onStart().
  3. UpdateService starts, i.e. onStart() is called, for intent 2.
  4. UpdateService stops because stopSelf() is called in onStart().

Could the two intents cause the service code, i.e onStart(), to run simultaneously? Do I need to put synchronized in the onStart() method definition?

Thanks.

+1  A: 

Could the two intents cause the service code, i.e onStart(), to run simultaneously?

No. The Service has onStart() called on the main application thread, and there is only one of those. Hence, the two Intents will be delivered sequentially. Which one is first, of course, is indeterminate.

BTW, it would be simpler if you extended IntentService, as that already handles the background thread for you -- anything you implement in onHandleIntent() is not executed on the main application thread.

CommonsWare
Thanks for your answer. It is very helpful.