探寻Android的线程问题

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

定时消息和线程在某个时间点才执行。 需要在另一个线程中去添加入队动作,而不是在本线程中。
注意:这里说的“消息”和Runnable对象、指令队列的概念是一样的。

回到Android上的Handler……如果你仔细阅读的话,可以看到文档是这样说的:

> A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

所以Handler可以让你给线程队列发消息:

> Each Handler instance is associated with a single thread and that thread's message queue.

一个Handler对象只能和一个线程关联:

> When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it

所以一个Handler到底和哪个线程关联呢?就是创造它的线程。

> — 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.、

在我们了解这些知识后,请继续看……

小贴士:这里有几点可能你还不知道。每个线程都和一个Handler类实例绑定,而且可以和别的线程一起运行,相互通信。

还有一个小建议(如果用过AsyncTask的话),AsyncTask内部也是使用Handler进行处理的,只是不是运行在UI线程而已,它会提供一个channel来和UI线程通信,使用postExecute方法即可实现。

这还挺酷的,那怎么创建Handler呢?

有两种方式:

使用默认的构造方法:new Handler()。 使用带参的构造方法,参数是一个Runnable对象或者回调对象。
Handler里面有什么实用的API吗?

请记住:

Handler只是简单往消息队列中发送消息而已(或者使用post方式) 它们有更方便的方法可以帮助与UI线程通信。
如果你现在看看Handler的API,可以清楚看到这几个方法:

post postDelayed postAtTime
代码示例

这里的代码都是很基础的,不过你可以好好看看注释。

示例1:使用Handler的“post”方法