探寻Android的线程问题

2019-12-10 18:43:48于海丽

使用AsyncTask是在Android上操作线程最简单的方式,也是最容易出错的方式。

3、IntentService

这种方式需要写更多的代码,但是这是把耗时任务移动到后台的很好的方式,也是我最喜欢的方式。配上使用一个EventBus机制的框架如Otto,这样的话实现IntentService就非常简单了。

4、Loader

关于处理异步任务,还有很多事情需要做,比如从数据库或者内容提供者那里处理一些数据。

5、Service

如果你曾经使用过Service的话,你应该知道这里会有一点误区,其中一个常见的误解就是服务是运行在后台线程的。其实不是!看似运行在后台是因为它们不与UI组件关联,但是它们(默认)是运行在UI线程上的……所以默认运行在UI线程上,甚至在上面没有UI部件。

如果想要把服务运行在后台线程中,那么必须自定义一个线程,然后把操作代码都运行在那个线程中(与上面提到的方法很类似)。事实上你应该使用IntentService实现,但是这不是本文讨论的主题。

Android上的Handler

以下是从Android developer documentation for Handlers:中摘选的一段话:

> A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread/message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

为了更好地了解这个概念,也许你需要去看看什么是Message Queues。

消息队列

在线程里基本都有一个叫做“消息队列”的东西,它负责线程间通信。这是一种设计模式,所有控制指令或者内容在线程间传递。

消息队列如同它的名字那样,对于线程来说,它就是一个指令队列。这里我们还可以做一些更酷的事: