本文介绍了异步任务 vs 线程 vs 服务 vs 加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Android 中 AsynctaskThreadServiceLoader 之间的差异有些困惑.

I got slightly confused about the differences between Asynctask, Thread, Service, Loader in Android.

我知道它是如何工作的.但我仍然不明白我应该在什么时候使用什么.

I know how it works. But i still don't understand what and when should i use.

我在 Android 上工作了 3 年,通常仍然使用 AsyncTask 来处理所有后台任务(有时还有 Thread).但是很多人说Asynctask 已经过时了",不推荐使用.他们还建议使用 robospice 或 Volley.

I work with Android for 3 years, and generally still use AsyncTask for all background tasks (and sometimes Thread). But many people say that "Asynctask is outdated", and don't recommend to use them. Also they recommend to use robospice or Volley.

那么,AsyncTask 真的那么糟糕,我应该使用框架来处理网络任务吗?我应该为后台(不是网络)任务使用什么?

So, is AsyncTask really so bad and i should use framework for networking tasks? And what should i use for background (not networking) task?

推荐答案

AysncTasks 并不像不完整那样过时".除其他事项外,异步任务不会打扰它们的父活动当前是否正在运行.出于同样的原因,您包括检查以验证上下文是否为空.此外,除非您使用自己的线程池执行器,否则这些任务是串行执行的.

AysncTasks are not 'outdated' as much as they are incomplete.Among other things async tasks do not bother if their parent activity is currently running or not. For the same reason why you include checks for verify the context to be null or not. Besides, unless you are using your own Thread Pool Executor these tasks execute serially.

Volley 试图填补这些空白,主要涉及与主线程和线程池同步.如果你想做需要平均网络请求的事情,它的行为是最佳的;像一些元数据列表和图像(图片 youtube 应用程序请求和 facebook 应用程序对帖子的请求).

Volley tries to fill in those gaps, mainly concerning syncing up with the main thread and thread pooling. It behaves optimal if you wish to do stuff that requires average network requests; like some meta data list and images(picture the youtube app requests and facebook app requests for posts).

Volley 的典型优势如下

Typically few advantages of Volley are as follows

  1. 它让工作线程了解活动(主线程)
  2. 更轻松地确定资源优先级,您可以为下载请求提供优先级.一个典型的场景是您将文本置于图像之上.
  3. 有效的请求缓存和内存管理.
  4. 可扩展
  5. 它为您提供了一个选项,以便在您的活动被关闭或重新启动时放弃您的请求.
  6. 与 AsyncTasks 不同的数据检索模式更简单.

在 Google I/O 上提到的流式请求/视频方面,Volley 表现不佳.

Volley fares badly when it comes to streaming requests/video as mentioned at Google I/O.

我并不完全了解机器人香料.Ps:如果你有时间看https://www.youtube.com/watch?v=yhv8l9F44qo

I'm not exactly aware of robospice.Ps: If you have time on your hand see https://www.youtube.com/watch?v=yhv8l9F44qo

如果您想进入其他具有相同基准的库,请阅读这里的进一步阅读.Android 网络库的比较:OkHTTP、Retrofit 和 Volley

Here's a further read if you wish to go into other libraries with benchmarks for the same.Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley

这篇关于异步任务 vs 线程 vs 服务 vs 加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:13