Handler源码分析

Handler 已经被无数人分析过了 为什么这里还要写篇博文分析呢,因为那是别人的,自己分析的才是你自己的

handler作用:(下面这段话摘自谷歌文档)
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own. 大概翻译一下: Handler有2个主要的作用:
(1)安排消息或Runnable在某个主线程中某个地方执行
(2)安排一个动作在不同的线程中执行

handler写法

子线程更新UI数据,需要使用如下代码发送消息给主线程处理:

//子线程中发送消息操作
Message message = handler.obtainMessage();
message.obj = "子线程更新的内容!";
handler.sendMessage(message);
最后会在主线程的Handler对象中执行handleMessage()方法:

Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        Object msgStr = msg.obj;
        if (msgStr != null) {
            tv_content.setText((String) msgStr);
        }
    }
};

源码分析
  为什么调用Handler就能在主线程更新UI呢?既然是源码分析就一步步的点进去看 首先看这一行代码做了什么

Message message = handler.obtainMessage();
调用了Message的obtain()方法

public static Message obtain(Handler h) {
    //调用了Message类中的静态方法obtain();
    Message m = obtain();
    //把上面传递进来的handler对象赋值给了m对象中的target成员变量
    m.target = h;
    //返回了Message m对象
    return m;
}

继续看obtain()方法:

public static Message obtain() {
    //同步代码块中的内容先跳过,第一次发送消息时sPool为null
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
//返回了一个Message对象
return new Message();

###总结:Message message = handler.obtainMessage();调用该方法时最后返回了一个new出来的Message()对象。

###接着看handler.sendMessage(message);

 public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

最终会调用

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);
    }

继续往下看enqueueMessage(queue, msg, uptimeMillis);

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

    synchronized (this) {
//根据if里打印的异常可以判断出这个mQuitting的意义是当在死亡线程中发送message时就会失败
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();//标记该消息正在使用
        msg.when = when;
        Message p = mMessages;//将MessageQueue中的mMessage对象赋值给一个新变量p
        boolean needWake;
     //第一次进入的时候,mMessage是为null的,也就是说说p是null
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
            msg.next = p;//把p赋值给了当前msg的下一个节点,看到这里就知道这里使用了链表
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

从这里可以看出把消息放到了队列中,那么只是放到队列中而已,再看看Handler构造方法

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());
            }
        }

//从ThreadLocal取出与handler绑定的Looper
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
//赋值Looper的MessageQueue给Handler
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

依旧没有看到handleMessage这个方法的调用,研究了半天,原来在ActivityThread这个类中, Android应用启动的入口都是从ActivityThread这个类的main()方法开始的

 public static final void main(String[] args) {
        SamplingProfilerIntegration.start();

        Process.setArgV0("");

//看到了Looper 划重点
        Looper.prepareMainLooper();
        if (sMainThreadHandler == null) {
            sMainThreadHandler = new Handler();
        }

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }


//看到了Looper 划重点
        Looper.loop();

        if (Process.supportsProcesses()) {
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }

        thread.detach();
        String name = (thread.mInitialApplication != null)
            ? thread.mInitialApplication.getPackageName()
            : "";
        Slog.i(TAG, "Main thread of " + name + " is now exiting");
    }

先分析下Looper.prepareMainLooper();

 public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

调用了prepare(false);以及 sMainLooper = myLooper();先看prepare()方法

 private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
//使用ThreadLocal存储了一个新创建的Looper,而且该looper对象不允许退出
        sThreadLocal.set(new Looper(quitAllowed));
    }

Looper构造函数

 private Looper(boolean quitAllowed) {
//创建一个MessageQueue对象并赋值给了自己的成员变量mQueue
        mQueue = new MessageQueue(quitAllowed);
//把当前线程赋值给了成员变量mThread
        mThread = Thread.currentThread();
    }

再看看myLooper()

只是把刚刚存到ThreadLocal的Looper对象取了出来而已!

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

到此,Looper.prepareMainLooper();方法已经全部执行完毕了!总结一下看他做了什么: 1.使用ThreadLocal存储了一个新创建的Looper,而且该looper对象不允许退出 2.创建一个MessageQueue对象并赋值给了自己的成员变量mQueue,把当前线程赋值给了成员变量mThread 3.取出Looper

还有Looper.loop();方法

public static void loop() {
    //执行该方法就是获取了上面创建的Looper对象
    final Looper me = myLooper();
    //只要执行了上面的prepare方法,这里就不会取出null
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    //拿到了上面创建的MessageQueue对象
    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
        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

      
   			final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
  //在这里 msg消息对应的target调用了dispatchMessage(msg)方法!刚才我们看到的target就是对应的handler对象,也就是说调用了每条消息对应的handler对象的dispatchMessage(msg)方法
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

        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();
    }
}

注意,当线程loop起来是时,线程就一直在循环中。就是说Looper.loop()后面的代码就不能被执行了。想要执行,需要先退出loop,这也就是为什么Looper.loop();放在最后后面的原因

接下来就要看msg.target.dispatchMessage(msg);

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

可以看出这里进行消息的处理

总结一下(采用面试问答形式)
问题一:Handler原理

1.最初在ActivityThread中,系统调用了一下Looper.prepareMainLooper();和Looper.loop()方法,所以在主线程中默认就会有一个Looper对象和与其绑定的MessageQueue对象。

2.通过obtain()获取Message对象(先从Message对象池中拿没有就new一个),并把Handler赋值给msg.target

3.sendToTarget()最终调用queue.enqueueMessage将消息插如MessageQueue中

4.Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue相关联。

5、prepare(boolean quitAllowed)会在本线程中保存一个Looper对象,然后该对象中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。

6、Looper.loop()会让当前线程进入一个无限循环,不断从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。

问题二:一个线程中有几个Looper几个Handler

一个线程只有一个Looper可以有多个Handler

问题三;什么时候会进入阻塞状态

1.消息队列中有消息,但是消息指定了执行的时间,而现在还没有到这个时间,线程会进入等待状态。 2.当消息队列中没有消息时,它会使线程进入等待状态;

问题四:MessageQueue是什么时候创建的

private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException(“Only one Looper may be created per thread”);
}
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

在线程主动调用Looper.prepare可以为当前线程主动创建一个Looper对象(主线程会自动生成一个Looper对象),MessageQueue在LOOper构造函数中创建

问题五:Handler是否会引发内存泄露
当Activity退出时消息队列中还有未处理的消息或者正在处理的消息 而消息队列中的Messager持有handler实例的引用(当使用内部类(包括匿名类)来创建Handler的时候,Handler对象会隐式地持有一个外部类对象(通常是一个Activity)的引用), 所以导致Activity的内存资源无法及时回收,引发内存泄露)

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、下4载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、下4载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值