【问题标题】:Extending the IntentService class扩展 IntentService 类
【发布时间】:2012-03-28 00:09:10
【问题描述】:

我刚刚在 Android 官方网站上找到了以下代码:

  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }

我还阅读了以下论文:

  • 创建一个默认工作线程,该线程执行传递给 onStartCommand() 的所有意图,与应用程序的主线程分开。
  • 创建一个工作队列,一次将一个意图传递给您的 onHandleIntent() 实现,因此您不必担心多线程。

所以如果 IntentService 使用工作线程并且我永远不必担心多线程,那么为什么我需要在 onHandleIntent(...) 方法中使用同步块?谢谢。

【问题讨论】:

    标签: java android


    【解决方案1】:

    所以如果 IntentService 使用工作线程并且我永远不必担心多线程,那么为什么我需要在 onHandleIntent(...) 方法中使用同步块?

    IntentService 一个工作线程。在该线程上调用onHandleIntent()

    但是,生命周期方法(onCreate()onStartCommand()onBind()onDestroy() 等)在主应用程序线程上调用。

    如果您尝试从工作线程和主应用程序线程中使用对象,您将需要通过一种或另一种方式同步它们的访问。

    顺便说一句,您引用的代码示例很奇怪,我不知道 Google 为什么要使用它。如果您需要睡觉(在生产应用中不常见),请使用SystemClock.sleep()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-22
      • 2016-02-26
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2010-10-12
      相关资源
      最近更新 更多