Looper Handler Message

本文深入探讨了Looper在Java中的实现原理及作用,着重解释了如何通过Looper和Handler来创建并管理消息循环,包括Looper的prepare、loop方法,以及Handler的sendMessageAtTime方法的具体使用场景和细节。
摘要由CSDN通过智能技术生成
 

Looper.java 分析

Class used to run a message loop for a thread.
Threads by default do not have a message loop associated with them; to create one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.

Most interaction with a message loop is through the Handler class.

This is a typical example of the implementation of a Looper thread, using the separation of prepare and loop to create an initial Handler to communicate with the Looper.

 

class LooperThread extends Thread {
      public Handler mHandler;
      
      public void run() {
		  //Initialize the current thread as a looper
		  // 创建消息队列
          Looper.prepare();
          
	  mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };
          
		  // 消息的处理 msg.target.dispatchMessage(msg);
          Looper.loop();
      }
  }

 

 

public boolean sendMessageAtTime(Message msg, long uptimeMillis)
    {
        boolean sent = false;
        // Looper.prepare()创建的队列
        MessageQueue queue = mQueue;
        if (queue != null) {
            // 把消息目标设成自己,在Looper.loop()里进行消息处理;
            msg.target = this;
            sent = queue.enqueueMessage(msg, uptimeMillis);
        }
        else {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
        }
        return sent;
    }


 

 

public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
    }


 public static final void loop() {
        Looper me = myLooper();
        MessageQueue queue = me.mQueue;
        
        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        
        while (true) {
            Message msg = queue.next(); // might block
            //if (!me.mRun) {
            //    break;
            //}
            if (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }
                if (me.mLogging!= null) me.mLogging.println(
                        ">>>>> Dispatching to " + msg.target + " "
                        + msg.callback + ": " + msg.what
                        );
                msg.target.dispatchMessage(msg);
                if (me.mLogging!= null) me.mLogging.println(
                        "<<<<< Finished to    " + msg.target + " "
                        + msg.callback);
                
                // Make sure that during the course of dispatching the
                // identity of the thread wasn't corrupted.
                final long newIdent = Binder.clearCallingIdentity();
                if (ident != newIdent) {
                    Log.wtf("Looper", "Thread identity changed from 0x"
                            + Long.toHexString(ident) + " to 0x"
                            + Long.toHexString(newIdent) + " while dispatching to "
                            + msg.target.getClass().getName() + " "
                            + msg.callback + " what=" + msg.what);
                }
                
                msg.recycle();
            }
        }
    }


Looper 和 Handler 的同步关系

public class HandlerThread extends Thread {
	private Looper mLooper;

	HandlerThread(String name) {
		super(name);
	}
	
	protected void onLooperPrepared() {}

	public void run() {
		Looper.prepare();
		synchronized(this) {
			mLooper = Looper.myLooper();
			notifyAll();
		}
		onLooperPrepared();
		Looper.loop();
	}

	/**
	*	If this thread has been started, this method will block until the looper has been initialied.
	*/
	public Looper getLooper() {
		if (!isAlive()) {
			return null;
		}
		// If the thread has been started, wait until the looper has been created.
		synchronized(this) {
			while(isAlive() && mLooper == null) {
				try {
					wait();
				} catch (InterruptedException e) {
				}
			}
		}
		return mLooper;
	}

	public boolean quit() [
		Looper looper = getLooper();
		if (looper != null) {
			looper.quit();
			return true;
		}
		return false;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值