Android 线程消息循环机制

android.os.Looper:

Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来 使消息循环起作用,从消息队列里取消息,处理消息。

注:写在Looper.loop()之后的代码不会被立即执行,当调用后mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。


以下是Android API中的一个典型的Looper thread实现:
//Handler不带参数的默认构造函数:new Handler(),实际上是通过Looper.myLooper()来获取当前线程中的消息循环,
//而默认情况下,线程是没有消息循环的,所以要调用 Looper.prepare()来给线程创建消息循环,然后再通过,Looper.loop()来使消息循环起作用。
  class LooperThread extends Thread {
     
public Handler mHandler;

     
public void run() {
         
Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                 
// process incoming messages here
             
}
         
};

         
Looper.loop();
     
}
 
}

另,Activity的MainUI线程默认是有消息队列的。所以在Activity中新建Handler时,不需要先调用Looper.prepare()。

android.os.Handler:

Handler用于跟线程绑定,来向线程的消息循环里面发送消息、接受消息并处理消息。

以下是不带参数的Handler构造器:

public Handler() {       

  if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    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也是只有一个。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值