何时使用 Service、AsyncTask 或 Handler? [英] When to use a Service or AsyncTask or Handler?
问题描述
谁能告诉我真正的区别?
推荐答案
我的经验法则是,AsyncTask
适用于我想做与单个 Activity
和 Service
用于当我想做一些事情时,它会在启动它的 Activity 在后台进行.
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.
因此,如果我想在 Activity
中进行少量后台处理而不占用 UI,我将使用 AsyncTask
.然后,我将使用该 Activity
中的默认 Handler
将消息传回以确保更新发生在主线程上.在主线程上处理更新有两个好处: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.
例如,如果我想做一个可能需要一段时间的下载,我会使用Service
.因此,如果我转到应用程序中的另一个 Activity
或其他应用程序,我的 Service
可以继续运行并继续下载文件,以便在我返回应用程序时准备就绪.在这种情况下,我可能会使用 状态栏通知 下载完成后,用户可以选择在方便时返回我的应用程序.
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
用于长时间运行的进程,您会发现它在您离开 Activity
后可能会继续,但是:
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:
- 如果处理完成时
Activity
在后台,当您尝试使用结果等更新 UI 时可能会遇到问题. - 后台
Activity
在需要内存时比Service
更有可能被Android杀死.
- 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
.
这篇关于何时使用 Service、AsyncTask 或 Handler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!