扩展IntentService类 [英] Extending the IntentService class

查看:177
本文介绍了扩展IntentService类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现下面就Android官方网站code:

  @覆盖
  保护无效onHandleIntent(意向意图){
      //通常我们会在这里做了一些工作,比如要下载的文件。
      //对于我们的示例,我们只是睡,持续5秒。
      长ENDTIME = System.currentTimeMillis的()+ 5 * 1000;
      而(System.currentTimeMillis的()<结束时间){
          同步(本){
              尝试{
                  等待(ENDTIME - System.currentTimeMillis的());
              }赶上(例外五){
              }
          }
      }
  }

和我也阅读以下文章:


  • 创建一个默认的工作线程执行交付给onStartCommand所有意图()从应用程序的主线程中分离出来。

  • 创建一个在同一时间到你onHandleIntent()实现通1意图,所以你永远不必担心多线程工作队列。

所以,如果IntentService使用工作线程,我从来不用担心多线程,那么为什么我需要onHandleIntent(...)方法使用同步块?谢谢你。


解决方案

  

所以,如果IntentService使用工作线程,我从来不用担心多线程,那么为什么我需要onHandleIntent(...)方法?用同步块


IntentService 的工作线程。 onHandleIntent()被称为该线程。

然而,生命周期方法(的onCreate() onStartCommand() onBind( )的onDestroy()等)被称为主应用程序线程上。

如果会有你正试图从两个辅助线程和主应用程序线程使用的对象,您将需要通过某种方式或其他他们的同步访问。

顺便说一句,你举code样品是奇怪的,我不知道为什么谷歌正在使用它。如果你需要(在生产应用程序异常)睡觉,使用 SystemClock.sleep()

I have just found following code on official Android site:

  @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) {
              }
          }
      }
  }

And also I read the following thesis:

  • Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.

So if IntentService uses worker thread and I never have to worry about multi-threading then why I need to use synchronize block in onHandleIntent(...) method? Thank you.

解决方案

So if IntentService uses worker thread and I never have to worry about multi-threading then why I need to use synchronize block in onHandleIntent(...) method?

IntentService has a worker thread. onHandleIntent() is called on that thread.

However, lifecycle methods (onCreate(), onStartCommand(), onBind(), onDestroy(), etc.) are called on the main application thread.

If there will be objects you are trying to use from both the worker thread and the main application thread, you will need to synchronize their access by one means or another.

BTW, the code sample you cite is bizarre, and I have no idea why Google is using it. If you need to sleep (unusual in a production app), use SystemClock.sleep().

这篇关于扩展IntentService类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆