当使用服务或AsyncTask的或处理程序? [英] When to use a Service or AsyncTask or Handler?
问题描述
有人能告诉我在 TRUE 的区别?
Can someone tell me the TRUE difference?
推荐答案
我的经验法则是,一个的AsyncTask
是当我想要做的事绑单曲 code>活动和服务
是当我想要做一些开始它是在活动结束后,将进行背景。
My rule of thumb is that an AsyncTask
is for when I want to do something tied to single Activity
and a Service
is for when I want to do something that will carry on after the Activity which started it is in the background.
所以,如果我想要做后台处理在活动小一点
不占用用户界面,我会使用的AsyncTask
。然后,我将使用默认的处理程序
从活动
来传递消息回来,以保证更新发生在主线程。处理主线程上的更新有两个好处:UI更新正确的发生,你不必担心同步问题这么多。
So if I want to do a small bit of background processing in the Activity
without tying up the UI I'll use an AsyncTask
. I'll then use the default Handler
from that Activity
to pass messages back to ensure updates happen on the main thread. Processing the updates on the main thread has two benefits: UI updates happen correctly and you don't have to worry so much about synchronisation problems.
如果举例来说,我想做一个下载可能需要一段时间,我会使用一个服务
。所以,如果我去了另一个活动
在我的应用程序或其他应用程序完全是我的服务
可以继续运行,并保持下载文件所以,当我回到我的应用程序将准备就绪。在这种情况下,我可能会使用状态栏通知一次下载完成,因此用户可以选择回到我的应用程序,只要是方便了他们。
If for example, I wanted to do a download which might take a while I'd use a Service
. So if I went to another Activity
in my application or another application entirely my Service
could keep running and keep downloading the file so it would be ready when I returned to my application. In this case I'd probably use a Status Bar Notification once the download was complete, so the user could choose to return to my application whenever was convenient for them.
你会发现如果你使用的AsyncTask
长期运行的过程中,你已经从活动导航离开后,可能继续
,但
What you'll find if you use an AsyncTask
for a long-running process it may continue after you've navigated away from the Activity
but:
- 如果在
活动
是在后台,当你处理完毕,你可能有问题,当你尝试的结果等来更新UI。 - 后台
活动
更有可能时,它需要的内存比一个服务
。<将由Android的杀害/ LI>
- If the
Activity
is in the background when your processing is complete you may have problems when you try to update the UI with the results etc. - A background
Activity
is far more likely to be killed by Android when it needs memory than aService
.
这篇关于当使用服务或AsyncTask的或处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!