本文共 2708 字,大约阅读时间需要 9 分钟。
Looper; //用作处理一个线程的消息循环。。主线程中,已经有一个Looper对象,只需要通过Handler提交Message即可。 //子线程中,需要创建Looper,有了Loop之后,就可以在本程序中,想这个Looper所在的线程发送消息。启动这个线程的处理。Loop.prepare(). public final class Looper extends Object{} 居多是静态方法 Looper.prepare();//把当前线程作为一个 Looper初始化 Looper.loop();//开始进行处理线程里的消息队列 Looper.myLooper();//获得当前线程的 Looper 对象 在另外启用的服务或者线程中,new 一个Handler对象,就是获得相关联的Looper对象。本地,就是获得mainlooper,远程就是一个新的looper。 new Handler 自动对Looper使用。√ √ √ √ √ MessageQueue Looper.myQueue();//获得 MessageQueue 对象 Looper Looper.getMainLooper();//获得主线程的 Looper 对象。 quit(); getThread();//返回这个 Looper 关联的线程。 Handler; //消息处理机制 //发送和处理和一个线程的消息队列相关联消息对象和Runnable对象。。Message就是签名的数据包而已。 //每一个Handler实例关联一个单独的线程,和一个线程的消息队列 作用: //1,制定未来消息对象和Runnable对象的执行计划(哪个时间点) //2,重新整理一个在和自己完全不同线程的消息队列 已经实现消息传递的方法: //post机制,允许你重新排列被消息队列接收和调用的 Runnable 对象。 post(Runnable); //向消息队列中添加 postAtTime(Runnable ,long) postDelayed(Runnable,long) //send 机制,允许你排列一个将要被 handleMessage方法处理的 Message 数据捆。 sendEmptyMessage(int); 只是提示一下。比post多点信息。 sendMessage(Message); //push 一个到消息队列的end处 sendMessageAtTime(Message,long) sendMessageDelayed(Message,long) 方法: Handler();//使用当前 Looper 对象Handler(Looper.getLooper) Handler(Looper looper); //可以在别的线程使用主线程的Looper创建Handler。new Handler(Looper.getMainLooper()); dispatchMessage(Message); handleMessage(Message );//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< hasMessage(int what); obtainMessage(); //从全局消息池获得 obtainMessage(int what[,int arg1,int arg2]); removeMessage(int what);//清空消息队列里的内容 MessageQueue; //Low-level class holding the list of messages to be dispatched by a Looper. Message; //属性 int arg2; int arg1; Object obj; int what; //方法: getTarget();getWhen(); setData(Bundle);Bundle getData();peekData(); setTarget(Handler ); getTarget(); Message Message.obtain(); Message Message.obtain(Handler); Message Message.obtain(Handler h,int what); Thread;//java基础内容 // 1 ,其他线程内部的消息循环 class MyThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); //在当前的线程创建Looper对象。(内置new Looper到线程池中) //Looper中内置对 MessageQueue 的管理。进行for(;;)死循环。 messageQueue.next()为阻塞方法,等待消息。 mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } } // 2 ,新建线程,发送到新建的handler 对象。(本线程的循环,也就是说 MainLoop在UI线程中执行) Handler MyHandler = new Handler(){ public void handleMessage(Message msg){ *****; *** = ***msg.obj; ***; } }; new Thread( new Runnable(){ public void run(){ ********; ****; Message msg = Message.obtain(); msg.obj=***; msg.what=1; MyHandler.sendMessage(msg); } }).start(); // 3 , 控件的 Post 方法 //相当于直接用handler post到messageQueue,进行运行不需要回调handlerMessage()。 public boolean post(Runnable action); myTextView.post(new Runnable(){ public void run(){ myTextView.setText("new text ."); } });转载地址:http://obegi.baihongyu.com/