【问题标题】:Could be conflict due to two service intents to the same service?由于对同一服务的两个服务意图可能会发生冲突吗?
【发布时间】:2010-03-30 23:12:33
【问题描述】:

我只是想知道如果两个服务意图同时发送到同一个服务会不会有冲突。我的代码如下:

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

假设 UpdateService 同时有两个意图,意图 1 和意图 2。据我了解,只有一个 UpdateService 实例。那么,这两个意图会导致服务代码像下面的工作流一样顺序运行吗?

  1. UpdateService 启动,即 onStart() 被调用,用于意图 1。
  2. UpdateService 停止,因为在 onStart() 中调用了 stopSelf()。
  3. UpdateService 启动,即 onStart() 被调用,用于意图 2。
  4. UpdateService 停止,因为在 onStart() 中调用了 stopSelf()。

这两个意图是否会导致服务代码(即 onStart())同时运行?我需要在 onStart() 方法定义中加入 synchronized 吗?

谢谢。

【问题讨论】:

    标签: android


    【解决方案1】:

    这两个意图会导致 服务代码,即 onStart(),运行 同时?

    没有。 Service 在主应用程序线程上调用了onStart(),并且只有其中一个。因此,两个Intents 将按顺序交付。当然,哪个是第一个是不确定的。

    顺便说一句,如果你扩展IntentService 会更简单,因为它已经为你处理了后台线程——你在onHandleIntent() 中实现的任何东西都不会在主应用程序线程上执行。

    【讨论】:

    • 感谢您的回答。很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    相关资源
    最近更新 更多