有人可以告诉我在 TRUE 的区别?
Can someone tell me the TRUE difference?
我的经验法则是,一个的AsyncTask
是当我想要做的事情依赖于单一的活动
和服务
是当我想要做一些东西,开始是在活动结束后,将进行以背景。
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.
所以,如果我想要做的后台处理的活动小一点
不占用我会用UI中的的AsyncTask
。然后,我将使用默认的处理程序
从活动
来传递讯息传回,以确保更新发生在主线程。处理主线程上的更新有两个好处:用户界面更新发生正确,你不必太担心同步问题
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。
系统背景活动
更有可能被机器人杀死时,它需要的内存比一个服务
。
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 a Service
.