最近复习到了Handler一直只知道怎么用,却没有仔细分析过源码,这下就来看看安全
为何要使用handler呢?并发
由于在安卓应用中ui操做是线程安全的,只能ui线程去操做ui组件,可是在现实开发中,可能有多个线程去并发操做ui,因此将会致使线程不安全,因此就用到了handlerasync
Looper1.主要负责建立message Queue和自身的建立 2. 消息的循环ide
public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { //判断当前的对象是否为空 ,即prepare不能调用两次 if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } 建立looper对象放入线程中 sThreadLocal.set(new Looper(quitAllowed)); }
private Looper(boolean quitAllowed) { //looper对象建立了messagequeue mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
2.looper.loopoop
public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final 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(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { //吧msg交给msg.target实际就是绑定的handler去处理这个方法中调用了handlemessage因此在建立handler 的时候要重写handlemessage方法 msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } if (logging != null) { logging.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(TAG, "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.recycleUnchecked(); } }
Looper的做用就是建立message队列,而后吧队列中的消息派发给handler,而后handler去处理消息post
而后咱们在去看下Handler的源码ui
public Handler(Callback callback, boolean async) { 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) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
能够看出handler建立的时候就会绑定他的looper并找见他的队列this
handler有两种发送消息的方法 send和postspa
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } //看出来最后调用了队列的方法,也就是handler发出的消息,最后会保存到对应的队列中 return queue.enqueueMessage(msg, uptimeMillis); }
因此就是一个应用的建立,系统会自动给你生成一个主线程,并在这个主线程中生成一个Looper对象来让你和子线程之间进行消息的传递,Looper会建立一个消息队列,当咱们在子线程中给主线程发消息的时候就须要用到handler,handler建立的时候就会去找到这个对应的looper。looper不断的执行loop方法去发消息给队列中 ,没当handler去发送一个消息的时候,就吧消息加入到队列中 ,而后队列的loop方法就会接收到这个消息,而后消息去调用dispatchmsg方法,而后dispatchmsg方法就会调用handler中的handlemessage方法,咱们就能接收到这个消息线程