问题描述
为什么我读的答案,在这里大多数问题了很多关于 的AsyncTask
和装载机,但没有关于服务?难道只是服务不为人熟知或者他们去precated还是有一些不好的属性什么的?有什么区别?
Why do I read in the answer to most questions here a lot about AsyncTask
and Loaders but nothing about Services? Are Services just not known very well or are they deprecated or have some bad attributes or something? What are the differences?
(顺便说一句,我知道有关于它的其他线程,但没有真正指出明显的差异,以帮助开发人员轻松地决定他是最好使用一种或另一种的一个实际问题。)
(By the way, I know that there are other threads about it, but none really states clear differences that help a developer to easily decide if he is better off using the one or the other for an actual problem.)
推荐答案
在某些情况下,可以完成同样的任务符合任何一个的AsyncTask
或服务
但通常是一个更适合比其他的任务。
In some cases it is possible to accomplish the same task with either an AsyncTask
or a Service
however usually one is better suited to a task than the other.
的AsyncTask
s的设计为一次性的UI线程无法运行耗时的任务。一个常见的例子是读取/处理数据时,一个按钮是pressed。
AsyncTask
s are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.
服务
s的设计为不断在后台运行。在上面获取数据时的一个按钮是pressed的例子,你可以启动一个服务,让它获取数据,然后就停下来了,这是低效的。这是远远快于使用的AsyncTask
将运行一次,返回数据,并完成。
Service
s are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask
that will run once, return the data, and be done.
如果您需要继续做的事情的背景下,虽然,一个服务
是你最好的选择。这方面的例子包括:播放音乐,不断地检查新数据,等等。
If you need to be continually doing something in the background, though, a Service
is your best bet. Examples of this include playing music, continually checking for new data, etc.
另外,谢里夫已经说了,服务并不一定关闭UI线程上运行。
Also, as Sherif already said, services do not necessarily run off of the UI thread.
在大多数情况下,服务
是因为当你想甚至可以运行code,当你的应用程序的活动
不开。 的AsyncTask
s的设计,使执行code关闭UI线程非常简单的。的
For the most part, Service
s are for when you want to run code even when your application's Activity
isn't open. AsyncTask
s are designed to make executing code off of the UI thread incredibly simple.
这篇关于安卓的AsyncTask VS服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!