读书人

Android 线程讯息循环机制

发布时间: 2012-07-19 16:02:20 作者: rapoo

Android 线程消息循环机制

android.os.Looper:Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来??????????????????? klass.getCanonicalName());
??????????? }
??????? }

??????? mLooper = Looper.myLooper();
??????? if (mLooper == null) {

//如果当前线程里面没有消息循环的时候,系统抛出异常。即在一个线程里如果想用Handler来处理消息,是需要调用Looer.prepare()来创建消息循环的,而MainUI线程不需要。

??????????? throw new RuntimeException(
??????????????? "Can't create handler inside thread that has not called Looper.prepare()");
??????? }
??????? mQueue = mLooper.mQueue;
??????? mCallback = null;
??? }

通过以下函数来向线程发送消息或Runnable: 1、post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long);  当线程接收到Runnable对象后即立即或一定延迟调用。2、sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long)。  当线程接受到这些消息后,根据你的Handler重构的handleMessage(Message)根据接收到的消息来进行处理。另,一个Activity主线程中可以有多个Handler对象,但MessageQueueLooper是只有一个,对应的Looper也是只有一个。
转自:http://www.cnblogs.com/wumao/archive/2011/04/24/2026421.html

读书人网 >Android

热点推荐