Handler&Message初见


title: Handler&Message入门

除了AsyncTask之外,Android还提供了其他的线程操作,如Handler、Message、MessageQueue、Looper等模块,这些就是Android的消息处理机制,难

Handler简介

​ 一个Handler会允许你发送和处理Message或者Runnable对象关联到一个线程的消息队列MessageQueue中。每一个Handler实例都会关联到一个单一线程和线程的消息队列。当你创建一个一个新的Handler,它会绑定到你创建的线程和这个线程消息队列中。随后,他就会将Messages和Runnables传递到消息队列,然后当他们出现在消息队列时,执行。

​ There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.


Message简介

Defines a message containing a description and arbitrary data object that can be sent to a Handler. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.

我已经见过的用法

Message.obj = ......

An arbitrary object to send to the recipient. When using Messenger to send the message across processes this can only be non-null if it contains a Parcelable of a framework class (not one implemented by the application). For other data transfer use setData(Bundle).

Message.what = 3

User-defined message code so that the recipient can identify what this message is about. Each Handler has its own name-space for message codes, so you do not need to worry about yours conflicting with other handlers.


Message message = new Message();
message.what = 3;
message.obj = socket.getRemoteDevice();
handler.sendMessage(message);

To Be Continued!!!

你可能感兴趣的:(Handler&Message初见)