服务V / S的AsyncTask [英] Service v/s AsyncTask

查看:94
本文介绍了服务V / S的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑相对于我的应用程序的设计。我需要不断地轮询服务器,以从中获取新的数据。我很困惑异步任务是否运行在固定的时间间隔或服务的运行是背景是更好的选择。应用程序运行时,线程才能运行。

I am confused with respect to design of my app. I need to continuously poll a server to get new data from it. I am confused whether Async Task running at fixed interval or Service running is background is better option. The thread will run only when the app is running

推荐答案

您已经有些答复你的问题,但我认为这一点,实在值得总结...

You have already some answers to your question, but I think it worths a summary ...

你需要什么

当您要运行code的peice的,需要一些时间来完成,你总是应该从UI线程独立的线程中运行它。

When you want to run a peice of code that takes some time to complete you should always run it in a separate thread from the UI thread.

您可以实现在2种方式:

You can achieve that in 2 ways:

使用

这是最简单的一种,如果不从新线程到UI线程需要大量的沟通。如果你需要沟通,你可能会使用处理程序来做到这一点。

This is the simplest one, if you don't need a lot of communication from the new thread to the UI thread. If you need the communication, you will probably have to use a Handler to do it.

使用的AsyncTask

此外,在一个单独的线程运行,并且已经实现了与UI线程一些沟通渠道。因此,这一个是preferable如果你需要这种沟通回UI。

Also runs in a separate thread and already implements some communications channels with the UI thread. So this one is preferable if you need this communication back to the UI.

你不需要什么

服务

这主要用来保留一些code退出即使在主应用程序,除非你使用产卵上述选择一个新的线程,将在UI线程在运行了。你说你的线程都suposed,当您退出应用程序终止,所以这不是你所需要的。

This serves mainly to keep some code running even after you exit the main application, and it will run in the UI thread unless you spawn a new thread using the options described above. You said that your thread are suposed to terminate when you exit application, so this is not what you need.

IntentService

这可以通过就可以开始了一块由您定义code,即使你的应用程序没有运行的外部事件(即广播接收器)被激活。再次,根据您的要求,这是不是你在找什么。

This can be activated by an external event (i.e. BroadcastReceiver) that can start a piece of code defined by you, even if your application is not running. Once again, based on your requirements, this is not what you are looking for.

问候。

这篇关于服务V / S的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆