且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android和QUOT;服务与QUOT;没有真正的背景是什么?

更新时间:2022-10-17 17:59:23

从手动


  

什么是服务?


  
  

大多数的混淆有关服务类实际上各地围绕什么
  它不是:


  
  

      
  1. 系统服务是的不可以一个单独的进程。服务对象本身并不
      并不意味着它是在它自己的进程运行;除非另有
      指定,在同一进程中运行的应用中它是部分
      的。

  2.   
  3. 系统服务是的不可以的线程。它不是一个装置本身做工作关
      主线程(以避免应用程序不响应错误)。

  4.   

块引用>

这是你应该怎么做(再次,从手动和放取;也@Jave提及):


  

注意,服务,如其他应用的目的,在主运行
  它们的宿主进程的线程。这意味着,如果你的服务是
  打算做任何CPU密集型(如MP3播放)或阻塞(如
  联网)操作,应该产卵它自己的线程,在其中
  做到这一点的工作。更多相关信息可以在进程和线程找到 。该 IntentService 类是作为一个标准
  实施服务的,有它自己的线程在那里时间表
  它的工作要做。


块引用>

I'm trying to play around with an Android "Service" but the more I play with it, the more I see that it's intimately tied to the UI thread. What I mean is that I fire up an Activity, and call a Service, just for yucks do a very long for loop in the Service. I would expect that for loop to happen in the "background" and not interfere with my UI, but it's freezing my UI while the for loop is going on (and it releases my UI back to normal when the for loop is done). Why wouldn't the "Service" just run in the "background" instead of messing up my UI? How can I make it run in the "background"?

from the manual:

What is a Service?

Most confusion about the Service class actually revolves around what it is not:

  1. A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
  2. A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

This is how you should do (again, taken from the manual & also mentioned by @Jave):

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.