当使用服务或AsyncTask的或处理程序?

编程入门 行业动态 更新时间:2024-10-10 19:27:14
本文介绍了当使用服务或AsyncTask的或处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人能告诉我在 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。
  • 后台活动更有可能时,它需要的内存比一个服务。
  • 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.

更多推荐

当使用服务或AsyncTask的或处理程序?

本文发布于:2023-11-27 13:17:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638233.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序   AsyncTask

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!