Android的消息机制

1.Android消息机制原理图:

 

2.Handler运行官方说明:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper. It will deliver messages and runnables to that Looper's message queue and execute them on that Looper's thread.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

3.Handler运行可以简述为:

Handler将Message发送到Looper的消息队列中,即MessageQueue,等待Looper的循环读取Message,处理Message,然后调用Message的target,即附属的Handler的dispatchMessage()方法,将该消息回调到handleMessage()方法中,然后完成更新UI操作。   

4.Handler的工作原理

Handler的工作主要包含消息的发送和接收过程。消息的发送可以通过post的一系列方法以及send的一系列方法来实现,post的一系列方法最终是通过send的一系列方法来实现的。

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("LooperH, 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);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

可以发现,Handler发送消息的过程仅仅是向消息队列中插入了一条消息, MessageQueue的next方法就会返回这条消息给Looper, Looper收到消息后就开始处理了, 最终消息由Looper交由Handler处理,即Handler的dispatchMessage方法会被调用,这时 Handler就进入了处理消息的阶段。dispatchMessage的实现如下所示。

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

Handler处理消息的过程如下:

首先,检查Message的callback是否为null,不为null就通过handleCallback来处理消息。Message的callback是一个Runnable对象,实际上就是Handler的post方法所传递的 Runnable参数。

其次,检査mCallback是否为null,不为null就调用mCallback的handleMessage方法来处理消息。

最后,调用Handler的handleMessage方法来处理消息。Handler处理消息的过程可以

归纳为一个流程图。

5.消息队列的工作原理

MessageQueue主要包含两个操作:插入和读取。插入和读取对应的方法分别为enqueueMessage 和next。尽管MessageQueue叫消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来维护消息列表,单链表在插入和删除上比较有优势。

boolean enqueueMessage(Message msg, long when) {
    synchronized (this) {
        msg.marklnUse ();
        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;
}

next的主要逻辑如下所示。

Message next(){
    int pendingldleHandlerCount = -1; // -1 only during first iteration int     
    nextPollTimeoutMiIlls = 0;
    for (;;)(
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
            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;
                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 = (int) Math.min(msg.when - now, Integer.MAX VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg !- null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages - msg.next;
                        }
                        msg.next = null;
                        if (false) Log. v ("MessageQueue'*, MReturning message:" + msg);
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
            }
        }
}

可以发现next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞在这里。当有新消息到来时,next方法会返回这条消息并将其从单链表中移除。

6.Looper的工作原理

 首先看一下它的构造方法,在构造方法中它会创建一个MessageQueue即消息队列,然后将当前线程的对象保存起来,如下所示。

private Looper(boolean quitAllowed) (
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

我们知道,Handler的工作需要Looper,没有Looper的线程就会报错,那么如何为一 个线程创建Looper呢?其实很简单,通过Looper.prepare。即可为当前线程创建一个Looper, 接着通过Looper.loop来开启消息循环,如下所示。

new Thread("Thread#2") {

    @Override
    public void run() {
        Looper.prepare();
        Handler handler = new Handler();
        Looper.loop();
    };
}・start ();

Looper提供了 quit和quitSafely 来退岀一个Looper,二者的区别是:quit会直接退出Looper,而quitSafely只是设定一个退出标记,然后把消息队列中的已有消息处理完毕后才安全地退出。Looper退出后,通过 Handler发送的消息会失败,这个时候Handler的send方法会返回false。在子线程中,如果手动为其创建了 Looper,那么在所有的事情完成以后应该调用quit方法来终止消息循环, 否则这个子线程就会一直处于等待的状态,而如果退出Looper以后,这个线程就会立刻终止,因此建议不需要的时候终止Looper。

Looper最重要的一个方法是loop方法,它的实现如下所示。

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.clearCallingldentity();
    final long ident = Binder.clearCallingldentity();
    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.printin (">>> Dispatching to " + msg. target + " " +msg.callback + ": " + msg.what);
         }

         msg.target.dispatchMessage(msg);
         if (logging != null) {
             logging .printin ("<<< Finished to " + msg. target + msg.callback);
             // Make sure that during the course of dispatching the
             // identity of the thread wasn't corrupted,

             final long newldent = Binder.clearCallingldentity();
             if (ident != newldent) {
                 Log.wtf(TAG, "Thread identity changed from Ox"+ Long.toHexString(ident) + ” to Ox"+ Long.toHexString(newldent)+n while dispatching to + msg.target.getClass().getName() + ""+ msg.callback + n what=n + msg.what);
             }
          }
        msg.recycleUnchecked();
    }
}

Looper的loop方法的工作过程也比较好理解,loop方法是一个死循环,唯一跳岀循环 的方式是MessageQueue的next方法返回了 null.当Looper的quit方法被调用时,Looper 就会调用MessageQueue的quit或者quitSafely方法来通知消息队列退出,当消息队列被标记为退出状态时,它的next方法就会返回null。

Looper和ThreadLocal之间的联系,如下代码所示

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

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

Looper在prepare时,就通过ThreadLocal将新建的Looper保存起来,当需要Looper对象时就通过Looper的静态方法myLooper将ThreadLocal中保存的Looper对象取出。 

7.ThreadLocal 的工作原理

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。

只要弄清楚 ThreadLocal 的get和set方法就可以明白它的工作原理。

首先看ThreadLocal的set方法,如下所示。

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

上面分析了 ThreadLocal的set方法,这里分析它的get方法,如下所示。

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

总结 :
ThreadLocal对象的set/get方法都是操作的当前线程的ThreadLocalMap对象,所以ThreadLocal并不是存放数据的地方,它只是代理了线程ThreadLocalMap容器的set/get方法。画一个示意图就知道了:  

ThreadLocal的get方法的key是当前的ThreadLocal.hashcode,而容器是所在线程的map,这两者决定了获取的对象是哪个。

8.主线程的消息循环

Android的主线程就是ActivityThread,主线程的入口方法为main,在main方法中系统会通过Looper.prepareMainLooper()来创建主线程的Looper以及MessageQueue»并通过 Looper.loop。来开启主线程的消息循环,这个过程如下所示。

public static void main(String[] args) (

    Process.setArgV0("<pre-initialized>");
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    AsyncTask.init();
    if (false) {
        Looper.myLooper().setMessageLogging(newLogPrinter(Log.DEBUG, "ActivityThread"));
    }
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

主线程的消息循环开始了以后,ActivityThread还需要一个Handler来和消息队列进行 交互,这个Handler就是ActivityThread.H,它内部定义了一组消息类型,主要包含了四大 组件的启动和停止等过程,如下所示。

private class H extends Handler {

    public static final int LAUNCH_ACTIVITY    =100;
    public static final int PAUSE_ACTIVITY    =101;
    public static final int PAUSE_ACTIVITY_FINISHING    =102;
    public static final int STOP_ACTIVITY_SHOW    =103;
    public static final int STOP_ACTIVITY_HIDE    =104;
    public static final int SHOW__W INDOW    =105;
    public static final int HIDE_WINDOW    =106;
    public static final int RESUME_ACTIVITY    =107;
    public static final int SEND_RESULT    =108;
    public static final int DESTROY_ACTIVITY    =109;
    public static final int BIND_APPLICATION    =110;
    public static final int EXIT_APPLICATION    =111;
    public static final int NEW_INTENT    =112;
    public static final int RECEIVER    =113;
    public static final int CREATE_SERVICE    =114;
    public static final int SERVICE_ARGS    =115;
    public static final int STOP_SERVICE    =116;
}

ActivityThread通过ApplicationThread和AMS进行进程间通信,AMS以进程间通信的 方式完成ActivityThread的请求后会回调ApplicationThread中的Binder方法,然后 ApplicationThread会向H发送消息,H收到消息后会将ApplicationThread中的逻辑切换到 ActivityThread中去执行,即切换到主线程中去执行,这个过程就是主线程的消息循环模型。

这是一个基于AI视觉识别与3D引擎技术打造的沉浸式交互圣诞装置。 简单来说,它是一棵通过网页浏览器运行的数字智慧圣诞树,你可以用真实的肢体动作来操控它的形态,并将自己的回忆照片融入其中。 1. 核心技术组成 这个作品是由三个尖端技术模块组成的: Three.js 3D引擎:负责渲染整棵圣诞树、动态落雪、五彩挂灯树顶星。它创建了一个具备光影深度感的虚拟3D空间。 MediaPipe AI手势识别:调用电脑摄像头,实时识别手部的21个关键点。它能读懂你的手势,如握拳、张开或捏合。 GSAP动画系统:负责处理粒子散开与聚合时的平滑过渡,让成百上千个物体在运动时保持顺滑。 2. 它的主要作用与功能 交互式情感表达: 回忆挂载:你可以上传本地照片,这些照片会像装饰品一样挂在树上,或者像星云一样环绕在树周围。 魔法操控:握拳时粒子迅速聚拢,构成一棵挺拔的圣诞树;张开手掌时,树会瞬间炸裂成星光雪花,照片随之起舞;捏合手指时视线会拉近,让你特写观察某一张选中的照片。 节日氛围装饰: 在白色背景下,这棵树呈现出一种现代艺术感。600片雪花在3D空间里缓缓飘落,提供视觉深度。树上的彩色粒子白色星灯会周期性地呼吸闪烁,模拟真实灯串的效果。 3. 如何使用 启动:运行代码后,允许浏览器开启摄像头。 装扮:点击上传照片按钮,选择温馨合照。 互动:对着摄像头挥动手掌可以旋转圣诞树;五指张开让照片树化作满天星辰;攥紧拳头让它们重新变回挺拔的树。 4. 适用场景 个人纪念:作为一个独特的数字相册,在节日陪伴自己。 浪漫惊喜:录制一段操作手势让照片绽放的视频发给朋友。 技术展示:作为WebGL与AI结合的案例,展示前端开发的潜力。
【顶级EI复现】计及连锁故障传播路径的电力系统 N-k 多阶段双层优化及故障场景筛选模型(Matlab代码实现)内容概要:本文提出了一种计及连锁故障传播路径的电力系统N-k多阶段双层优化及故障场景筛选模型,并提供了基于Matlab的代码实现。该模型旨在应对复杂电力系统中可能发生的N-k故障(即多个元件相继失效),通过构建双层优化框架,上层优化系统运行策略,下层模拟故障传播过程,从而实现对关键故障场景的有效识别与筛选。研究结合多阶段动态特性,充分考虑故障的时序演化与连锁反应机制,提升了电力系统安全性评估的准确性与实用性。此外,模型具备良好的通用性与可扩展性,适用于大规模电网的风险评估与预防控制。; 适合人群:电力系统、能源互联网及相关领域的高校研究生、科研人员以及从事电网安全分析、风险评估的工程技术人员。; 使用场景及目标:①用于电力系统连锁故障建模与风险评估;②支撑N-k故障场景的自动化筛选与关键脆弱环节识别;③为电网规划、调度运行及应急预案制定提供理论依据技术工具;④服务于高水平学术论文复现与科研项目开发。; 阅读建议:建议读者结合Matlab代码深入理解模型构建细节,重点关注双层优化结构的设计逻辑、故障传播路径的建模方法以及场景削减技术的应用,建议在实际电网数据上进行测试与验证,以提升对模型性能与适用边界的认知。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值