android 消息模型之 执行源码分析

1.在我看来 一个持续运行应用程序 就是main方法进入 ,然后在里面使用消息模型不断接受系统或者用户的请求并作出对应的处理.例如qt 的信号与槽 ,win32 消息映射(要自己实现) ,android 的handler+looper .他们共同的点一直做死循环,避免程序一运行就退出,  并且不断接受系统或者用户的请求并作出对应的处理

2.那么android应用 最开始是在哪个类进行死循环的呢,答案就在ActivityThread 类中 代码如下:

 public static void main(String[] args) {
    .....

        Looper.prepareMainLooper(); //创建ui线程的looper 

        ActivityThread thread = new ActivityThread(); 创建 thread 同时也是创建handler H
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
           //如果 mLogging 对象 不为空,可以在消息处理前后打印日志 看门狗貌似使用者两者之间的打印时间差来判断是否卡顿
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
// 这里就是做死循环不断接受请求和处理请求了.

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

如果你曾经在 子线程中创建过handler 了 ,那么这段代码就非常熟悉了.

3.使用handler 第一步 Looper.prepareMainLooper

 public static void prepareMainLooper() {
        prepare(false);// 这里会创建 主looper ,并设置不允许退出,退出时会抛异常
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper(); //以当前线程为key取出looper对象.
        }


    }

 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); //创建存储消息的队列 这个比较重要 因为looper像个调度器 基本都是使用message 或者messagequeue 的方法
        mThread = Thread.currentThread();
    }

当然我们一般用的是prepare()方法

3.使用handler 第二步 消息队列对象MessageQueue创建(核心这个).消息队列负责对消息的管理和对线程的堵塞与唤醒

    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }
nativeInit 是本地方法, 作用就是创建native 层messagequeue 和looper .并在looper 中创建一个文件描述符.使用poll 来实现堵塞 .通过使用write写东西来poll  不堵塞.对应着nativePollOnce和nativeWake本地方法.具体看源码

里面重要的属性是:mMessages 消息队列头(单链表来管理的不是队列) ,mPtr指向native 的队列对象
重要方法next:
     
      Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null; //当loop 退出或者销毁
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands(); //刷新 binder 驱动
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);//处理native层消息或者堵塞用

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
              //当链表不为空 handler 为空 .一般handler 不为空 那直接跳下一步
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    //一般是默认同步 那直接跳下一步
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
 // 链表不为空 但未到执行时间, 再次循环将堵塞 堵塞时间为nextPollTimeoutMillis .
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
//执行时间已到
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;//handler 一般不为空否则毫无意义 跳过
                        } else {
                            mMessages = msg.next; //把下个消息对象赋值给链表头
                        }
                        msg.next = null;//引用置空有利回收
                        if (false) Log.v("MessageQueue", "Returning message: " + msg);
//返回一个消息对象
                        return msg;
                    
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1; //无限循环
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose(); //销毁native 层的队列
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
// 默认为空 跳过
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true; //如果不返回一个消息对象下次循环必然是堵塞 
                    continue;  //默认不执行下面的 所以.....
                }

           .........
    }
重要方法enqueueMessage: 把消息添加到链表中
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
      //这里就抛异常了 所以上面不会出现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) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse(); //标记正在使用
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
// 当链表为空,when==0 ,头消息对象时间大于所要加入消息对象时间 就直接把要添加的消息对象当做头 
                msg.next = p;
                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) {
// 唤醒 .假设 你先发送延迟两秒后执行的p1消息,然后再发送延迟一秒后执行的p2消息
//这时候p2 已经为头链表对象了 ,我不可能堵塞2秒吧肯定先唤醒再堵塞一秒吧
                nativeWake(mPtr);
            }
        }
        return true;
    }

  



4.第三步 handler 创建: 作用为将消息添加到消息链表中和处理消息

   public Handler(Callback callback, boolean async) {
//静态属性,匿名类,内部类..提示内存溢出.
  1.静态属性生命周期比activity长 无法回收造成的内存泄漏
  2.匿名类虽然生命周期相同,可是消息队列(message 持有handler ,handler 持有activity)生命比activity 长 无法回收造成的内存泄漏.所以activity 退出时删除所有消息.
        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();//从当前线程获取looper
        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;
    }

常用方法:sendMessage
      public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
//最后会调用queue.enqueueMessage 方法加入消息链表中(第二步说过略过)
  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    } 
常用方法:dispatchMessage 处理消息

   public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
//msg 的回调不为空将执行 msg.callback.run()方法
            handleCallback(msg);
        } else {
            if (mCallback != null) {
 //传入的回调返回true 将不执行handlMessage
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
//自定义略过
            handleMessage(msg);
        }
    }

5.使用handler第4步 Looper.loop 无限循环:从消息链表中获取message 并回调handler.dispatchMessage(..)方法相对简单如果看懂上面的话

6.使用handler 第五步 发送消息sendMessage加入消息链表后,loop 会在合适的时间取出message 并回调handler.dispatchMessage(..)

ps:有时间画个图.不懂看老罗的源代码情景分析那本书

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值