Handler的理解
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.
Handler使你能够send 和 处理 与一个线程的消息队列相关的Message和Runnable对象。每一个Handler实例是和一个指定线程及其消息队列相关联的。Handler对象会被绑定到创建它的thread及其消息队列。然后你就可以delivere Message and Runnable 对象,handler 会按照顺序依次处理这些他们。
下面是实现的小例子
package hust.ophone.RunnableTry;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
public class RunnableTry extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sendMessage();
}
public void sendMessage() {
MHandler mHandler = new MHandler();
//Returns a new Message
from the global message pool. More efficient than creating and allocating new //instances. The retrieved message has its handler set to this instance (Message.target == this).
Message msg = mHandler.obtainMessage();
Log.v("TAG", msg.toString());
msg.sendToTarget();
}
class MHandler extends Handler {
public MHandler() {
}
public MHandler(Looper l) {
super(l);
}
@Override
public void handleMessage(Message msg) {
int count = 0;
while (count++ < 10) {
Log.d("TAG", "处理消息");
}
}
}
}
更多相关文章
- 线程池工具类
- Android传感器之磁场传感器
- 自定义线程池管理类
- Android线程间通信
- 2020年GitHub标星2.9K的Android基础——高级面试题合集!(金九银十
- 收藏-------Android应用程序组件Content Provider在应用程序之间
- Android插件化原理解析——Hook机制之动态代理
- Android(安卓)点击通知栏消息 跳转到指定的Fragment界面
- android wifi模块分析