Android平台中的Service vs IntentService

问题描述:

我正在寻找一个示例,该示例可以用IntentService完成,而不能用Service完成(反之亦然)?

I am seeking an example of something that can be done with an IntentService that cannot be done with a Service (and vice-versa)?

我也相信IntentService在不同的线程中运行,而Service不在.因此,据我所知,在自己的线程中启动服务就像启动IntentService.正确吗?

I also believe that an IntentService runs in a different thread and a Service does not. So, as far as I can see, starting a service within its own thread is like starting an IntentService. Is that correct?

Tejas Lagvankar编写了很好的

Tejas Lagvankar wrote a nice post about this subject. Below are some key differences between Service and IntentService.

何时使用?

  • Service 可以用于没有UI的任务中,但不能太长.如果需要执行长任务,则必须使用Service中的线程.

  • The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.

IntentService 可以用于长任务,通常不与主线程通信.如果需要通信,则可以使用主线程处理程序或广播意图.另一个使用情况是需要回调(意图触发的任务)时.

The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

如何触发?

  • 服务是通过调用方法startService()触发的.

  • The Service is triggered by calling method startService().

IntentService 使用Intent触发,它产生一个新的工作线程,并在该线程上调用方法onHandleIntent().

The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.

触发自

  • Service IntentService 可以从任何线程,活动或其他应用程序组件中触发.
  • The Service and IntentService may be triggered from any thread, activity or other application component.

运行

  • Service 在后台运行,但在应用程序的主线程上运行.

  • The Service runs in background but it runs on the Main Thread of the application.

IntentService 在单独的工作线程上运行.

The IntentService runs on a separate worker thread.

限制/缺点

  • 服务可能会阻止应用程序的主线程.

  • The Service may block the Main Thread of the application.

IntentService 无法并行运行任务.因此,所有连续的意图都将进入工作线程的消息队列,并将按顺序执行.

The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.

何时停止?

  • 如果实现了 Service ,则有责任在服务完成工作时通过调用stopSelf()stopService()来停止服务. (如果只想提供绑定,则不需要实现此方法.)

  • If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method).

在处理了所有启动请求之后, IntentService 会停止服务,因此您不必调用stopSelf().

The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf().