400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

Handler的原理有哪些

本篇内容主要讲解“Handler的原理有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Handler的原理有哪些”吧!

成都创新互联公司主要从事网站建设、网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务裕华,十余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575

总流程

开头需要建立个handler作用的总体印象,下面画了一个总体的流程图

Handler的原理有哪些

从上面的流程图可以看出,总体上是分几个大块的

相关知识点大概涉及到这些,下面详细讲解下!

Handler的原理有哪些

使用

先来看下使用,不然源码,原理图搞了一大堆,一时想不起怎么用的,就尴尬了

使用很简单,此处仅做个展示,大家可以熟悉下

演示代码尽量简单是为了演示,关于静态内部类持有弱引用或者销毁回调中清空消息队列之类,就不在此处展示了

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

从上面源码可知,handler的使用总的来说,分俩大类,细分三小类

收发一体

public class MainActivity extends AppCompatActivity {
    private TextView msgTv;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        msgTv = findViewById(R.id.tv_msg);

      	//消息收发一体
        new Thread(new Runnable() {
            @Override public void run() {
                String info = "第一种方式";
                mHandler.post(new Runnable() {
                    @Override public void run() {
                        msgTv.setText(info);
                    }
                });
            }
        }).start();
    }
}

收发分开

mCallback.handleMessage(msg)

public class MainActivity extends AppCompatActivity {
    private TextView msgTv;
    private Handler mHandler = new Handler(new Handler.Callback() {
        //接收消息,刷新UI
        @Override public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                msgTv.setText(msg.obj.toString());
            }
            //false 重写Handler类的handleMessage会被调用,  true 不会被调用
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        msgTv = findViewById(R.id.tv_msg);

        //发送消息
        new Thread(new Runnable() {
            @Override public void run() {
                Message message = Message.obtain();
                message.what = 1;
                message.obj = "第二种方式 --- 1"; 
                mHandler.sendMessage(message);
            }
        }).start();
    }
}

handleMessage(msg)

public class MainActivity extends AppCompatActivity {
    private TextView msgTv;
    private Handler mHandler = new Handler() {
        //接收消息,刷新UI
        @Override public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                msgTv.setText(msg.obj.toString());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        msgTv = findViewById(R.id.tv_msg);

        //发送消息
        new Thread(new Runnable() {
            @Override public void run() {
                Message message = Message.obtain();
                message.what = 1;
                message.obj = "第二种方式 --- 2";
                mHandler.sendMessage(message);
            }
        }).start();
    }
}

prepare和loop

大家肯定有印象,在子线程和子线程的通信中,就必须在子线程中初始化Handler,必须这样写

new Thread(new Runnable() {
    @Override public void run() {
        Looper.prepare();
        Handler handler = new Handler();
        Looper.loop();
    }
});
ActivityThread.java
...
public static void main(String[] args) {
    ...
    //主线程Looper
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    //主线程的loop开始循环
    Looper.loop();
	...
}
...

为什么要使用prepare和loop?我画了个图,先让大家有个整体印象

Handler的原理有哪些

具体看下每个步骤的源码,这里也会标定好链接,方便大家随时过去查看

Looper.java
...
 public static void prepare() {
    prepare(true);
}

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));
}
...
Handler.java
...
@Deprecated
public Handler() {
    this(null, false);
}

public Handler(@Nullable Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class 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 " + Thread.currentThread()
            + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
...
Looper.java
...
public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}
...
Looper.java
...
public static void loop() {
    final Looper me = myLooper();
    
    ...
    
    final MessageQueue queue = me.mQueue;

   	...

    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        ...
        
        try {
            msg.target.dispatchMessage(msg);
            if (observer != null) {
                observer.messageDispatched(token, msg);
            }
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } catch (Exception exception) {
            if (observer != null) {
                observer.dispatchingThrewException(token, msg, exception);
            }
            throw exception;
        } finally {
            ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
     
        ....

        msg.recycleUnchecked();
    }
}
...

收发消息

收发消息的操作口都在Handler里,这是我们最直观的接触的点

下方的思维导图整体做了个概括

Handler的原理有哪些

前置知识

在说发送和接受消息之前,必须要先解释下,Message中一个很重要的属性:when

when这个变量是Message中的,发送消息的时候,我们一般是不会设置这个属性的,实际上也无法设置,只有内部包才能访问写的操作;将消息加入到消息队列的时候会给发送的消息设置该属性。消息加入消息队列方法:enqueueMessage(...)

在我们使用sendMessage发送消息的时候,实际上也会调用sendMessageDelayed延时发送消息发放,不过此时传入的延时时间会默认为0,来看下延时方法:sendMessageDelayed

public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

这地方调用了sendMessageAtTime方法,此处!做了一个时间相加的操作:SystemClock.uptimeMillis() + delayMillis

后面会将这个时间刻赋值给when:when = SystemClock.uptimeMillis() + delayMillis

说明when代表的是开机到现在的一个时间刻,通俗的理解,when可以理解为:现实时间的某个现在或未来的时刻(实际上when是个相对时刻,相对点就是开机的时间点)

发送消息

发送消息涉及到俩个方法:post(...)和sendMessage(...)

Handler.java
...
//post
public final boolean post(@NonNull Runnable r) {
    return  sendMessageDelayed(getPostMessage(r), 0);
}

//生成Message对象
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

//sendMessage方法
public final boolean sendMessage(@NonNull Message msg) {
    return sendMessageDelayed(msg, 0);
}

public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

public boolean sendMessageAtTime(@NonNull 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);
}

///将Message加入详细队列 
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
                               long uptimeMillis) {
    //设置target
    msg.target = this;
    msg.workSourceUid = ThreadLocalWorkSource.getUid();

    if (mAsynchronous) {
        //设置为异步方法
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
...
MessageQueue.java
...
boolean enqueueMessage(Message msg, long when) {
   ...

    synchronized (this) {
        ...

        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.
            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) {
            nativeWake(mPtr);
        }
    }
    return true;
}
...

Handler的原理有哪些

接收消息

接受消息相对而言就简单多

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

分发消息

消息分发是在loop()中完成的,来看看loop()这个重要的方法

Looper.java
...
public static void loop() {
    final Looper me = myLooper();
    ...
    final MessageQueue queue = me.mQueue;
   	...
    for (;;) {
        //遍历消息池,获取下一可用消息
        Message msg = queue.next(); // might block
        ...
        try {
            //分发消息
            msg.target.dispatchMessage(msg);
            ...
        } catch (Exception exception) {
            ...
        } finally {
            ...
        }
        ....
        //回收消息,进图消息池
        msg.recycleUnchecked();
    }
}
...

遍历消息

遍历消息的关键方法肯定是下面这个

来看看这个Message中的next()方法吧

MessageQueue.java
...
Message next() {
    final long ptr = mPtr;
    ...

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
  		...
        //阻塞,除非到了超时时间或者唤醒
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            // 这是关于同步屏障(SyncBarrier)的知识,放在同步屏障栏目讲
            if (msg != null && msg.target == null) {
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            
            if (msg != null) {
                if (now < msg.when) {
                    //每个消息处理有耗时时间,之间存在一个时间间隔(when是将要执行的时间点)。
                    //如果当前时刻还没到执行时刻(when),计算时间差值,传入nativePollOnce定义唤醒阻塞的时间
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    mBlocked = false;
                    //该操作是把异步消息单独从消息队列里面提出来,然后返回,返回之后,该异步消息就从消息队列里面剔除了
                    //mMessage仍处于未分发的同步消息位置
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    //返回符合条件的Message
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }

            //这是处理调用IdleHandler的操作,有几个条件
        	//1、当前消息队列为空(mMessages == null)
            //2、已经到了可以分发下一消息的时刻(now < mMessages.when)
            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;
            }

            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

       
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler

            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        // Reset the idle handler count to 0 so we do not run them again.
        pendingIdleHandlerCount = 0;

        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }
}

总结下源码里面表达的意思

  1. next()内部是个死循环,你可能会疑惑,只是拿下一节点的消息,为啥要死循环?

    • 为了执行延时消息以及同步屏障等等,这个死循环是必要的

  2. nativePollOnce阻塞方法:到了超时时间(nextPollTimeoutMillis)或者通过唤醒方式(nativeWake),会解除阻塞状态

    • nextPollTimeoutMillis大于等于零,会规定在此段时间内休眠,然后唤醒

    • 消息队列为空时,nextPollTimeoutMillis为-1,进入阻塞;重新有消息进入队列,插入头结点的时候会触发nativeWake唤醒方法

  3. 如果 msg.target == null为零,会进入同步屏障状态

    • 会将msg消息死循环到末尾节点,除非碰到异步方法

    • 如果碰到同步屏障消息,理论上会一直死循环上面操作,并不会返回消息,除非,同步屏障消息被移除消息队列

  4. 当前时刻和返回消息的when判定

    • 消息when代表的时刻:一般都是发送消息的时刻,如果是延时消息,就是 发送时刻+延时时间

    • 当前时刻小于返回消息的when:进入阻塞,计算时间差,给nativePollOnce设置超时时间,超时时间一到,解除阻塞,重新循环取消息

    • 当前时刻大于返回消息的when:获取可用消息返回

  5. 消息返回后,会将mMessage赋值为返回消息的下一节点(只针对不涉及同步屏障的同步消息)

这里简单的画了个流程图

Handler的原理有哪些

分发消息

分发消息主要的代码是: msg.target.dispatchMessage(msg);

也就是说这是Handler类中的dispatchMessage(msg)方法

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

可以看到,这里的代码,在收发消息栏目的接受消息那块已经说明过了,这里就无须重复了

消息池

msg.recycleUnchecked()是处理完成分发的消息,完成分发的消息并不会被回收掉,而是会进入消息池,等待被复用

Message.java
...
void recycleUnchecked() {
    // Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
    flags = FLAG_IN_USE;
    what = 0;
    arg1 = 0;
    arg2 = 0;
    obj = null;
    replyTo = null;
    sendingUid = UID_NONE;
    workSourceUid = UID_NONE;
    when = 0;
    target = null;
    callback = null;
    data = null;

    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

来看下消息池回收消息图示

Handler的原理有哪些

既然有将已使用的消息回收到消息池的操作,那肯定有获取消息池里面消息的方法了

Message.java
...
public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

来看下从消息池取一个消息的图示

Handler的原理有哪些

IdleHandler

在MessageQueue类中的next方法里,可以发现有关于对IdleHandler的处理,大家可千万别以为它是什么Handler特殊形式之类,这玩意就是一个interface,里面抽象了一个方法,结构非常的简单

MessageQueue.java
...
Message next() {
    final long ptr = mPtr;
    ...

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
  		...
        //阻塞,除非到了超时时间或者唤醒
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
			...
            //这是处理调用IdleHandler的操作,有几个条件
        	//1、当前消息队列为空(mMessages == null)
            //2、未到到了可以分发下一消息的时刻(now < mMessages.when)
			//3、pendingIdleHandlerCount < 0表明:只会在此for循环里执行一次处理IdleHandler操作
            if (pendingIdleHandlerCount < 0
                && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                mBlocked = true;
                continue;
            }

            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

       
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler

            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        pendingIdleHandlerCount = 0;
        nextPollTimeoutMillis = 0;
    }
}

实际上从上面的代码里面,可以分析出很多信息

IdleHandler相关信息

总结

其他资讯

让你的专属顾问为你服务

0.0422s