user256239
user256239

Reputation: 18027

Could be conflict due to two service intents to the same service?

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.

Upvotes: 1

Views: 488

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007266

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.

Upvotes: 1

Related Questions