Android進階技術之——一文吃透Android的消息機制

来源:https://www.cnblogs.com/BlueSocks/archive/2022/04/11/16130270.html
-Advertisement-
Play Games

前言 為什麼要老藥換新湯 作為Android中 至關重要 的機制之一,十多年來,分析它的文章不斷,大量的內容已經被挖掘過了。所以: 已經對這一機制熟稔於心的讀者,在這篇文章中,看不到新東西了。 但對於還不太熟悉消息機制的讀者,可以在文章的基礎上,繼續挖一挖。 一般,諸如此類有關Android的消息機 ...


前言

為什麼要老藥換新湯

作為Android中 至關重要 的機制之一,十多年來,分析它的文章不斷,大量的內容已經被挖掘過了。所以:

  • 已經對這一機制熟稔於心的讀者,在這篇文章中,看不到新東西了。

  • 但對於還不太熟悉消息機制的讀者,可以在文章的基礎上,繼續挖一挖。

一般,諸如此類有關Android的消息機制的文章,經過簡單的檢索和分析,大部分是圍繞:

  • Handler,Looper,MQ的關係

  • 上層的Handler,Looper、MQ 源碼分析

展開的。單純的從這些角度學習的話,並不能 完全理解 消息機制。

這篇文章本質還是一次腦暴 ,一來:避免腦暴跑偏 ,二來:幫助讀者 捋清內容脈絡 。先放出腦圖:

腦暴:OS解決進程間通信問題

程式世界中,存在著大量的 通信 場景。搜索我們的知識,解決 進程間通信 問題有以下幾種方式:

這段內容可以泛讀,瞭解就行,不影響往下閱讀

管道

  • 普通管道pipe:一種 半雙工 的通信方式,數據只能 單向流動 ,而且只能在具有 親緣關係 的進程間使用。

  • 命令流管道s_pipe: 全雙工,可以同時雙向傳輸

  • 命名管道FIFO:半雙工 的通信方式,允許 在 無親緣關係 的進程間通信。

消息隊列 MessageQueue:

消息的鏈表,存放在內核 中 並由 消息隊列標識符 標識。消息隊列剋服了 信號傳遞信息少、管道 只能承載 無格式位元組流 以及 緩衝區大小受限 等缺點。

共用存儲 SharedMemory:

映射一段 能被其他進程所訪問 的記憶體,這段共用記憶體由 一個進程創建,但 多個進程都可以訪問。共用記憶體是 最快的 IPC 方式,它是針對 其他 進程間通信方式 運行效率低 而專門設計的。往往與其他通信機制一同使用,如 信號量 配合使用,來實現進程間的同步和通信。

信號量 Semaphore:

是一個 計數器 ,可以用來控制多個進程對共用資源的訪問。它常作為一種 鎖機制,防止某進程正在訪問共用資源時, 其他進程也訪問該資源,實現 資源的進程獨占。因此,主要作為 進程間 以及 同一進程內線程間 的同步手段。

套接字Socket:

與其他通信機制不同的是,它可以 通過網路 ,在 不同機器之間 進行進程通信。

信號 signal:

用於通知接收進程 某事件已發生。機制比較複雜。

我們可以想象,Android之間也有大量的 進程間通信場景,OS必須採用 至少一種 機制,以實現進程間通信。

仔細研究下去,我們發現,Android OS用了不止一種方式。而且,Android 還基於 OpenBinder 開發了 Binder 用於 用戶空間 內的進程間通信。

這裡我們留一個問題以後探究:

Android 有沒有使用 Linux內核中的MessageQueue機制 幹事情

基於消息隊列的消息機制設計有很多優勢,Android 在很多通信場景內,採用了這一設計思路。

消息機制的三要素

不管在哪,我們談到消息機制,都會有這三個要素:

  • 消息隊列

  • 消息迴圈(分發)

  • 消息處理

消息隊列 ,是 消息對象 的隊列,基本規則是 FIFO。

消息迴圈(分發), 基本是通用的機制,利用 死迴圈 不斷的取出消息隊列頭部的消息,派發執行

消息處理,這裡不得不提到 消息 有兩種形式:

  • Enrichment 自身信息完備

  • Query-Back 自身信息不完備,需要回查

這兩者的取捨,主要看系統中 生成消息的開銷 和 回查信息的開銷 兩者的博弈。

在信息完備後,接收者即可處理消息。

Android Framework

Android 的Framework中的消息隊列有兩個:

Java層 frameworks/base/core/java/android/os/MessageQueue.java

Native層 frameworks/base/core/jni/android_os_MessageQueue.cpp

Java層的MQ並不是 List 或者 Queue 之類的 Jdk內的數據結構實現。

Native層的源碼我下載了一份 Android 10 的 源碼(https://github.com/leobert-lan/Blog/blob/main/Android/Mechanism/Message/code/android_os_MessageQueue.cpp) ,並不長,大家可以完整的讀一讀。

並不難理解:用戶空間 會接收到來自 內核空間 的 消息 , 從 下圖 我們可知,這部分消息先被 Native層 獲知,所以:

  • 通過 Native層 建立消息隊列,它擁有消息隊列的各種基本能力

  • 利用JNI 打通 Java層 和 Native層 的 Runtime屏障,在Java層 映射 出消息隊列

  • 應用建立在Java層之上,在Java層中實現消息的 分發 和 處理

PS:在Android 2.3那個時代,消息隊列的實現是在Java層的,至於10年前為何改成了 native實現, 推測和CPU空轉有關,筆者沒有繼續探究下去,如果有讀者瞭解,希望可以留言幫我解惑。

PS:還有一張經典的 系統啟動架構圖 沒有找到,這張圖更加直觀

代碼解析

我們簡單的 閱讀、分析 下Native中的MQ源碼

Native層消息隊列的創建:



static jlong android\_os\_MessageQueue\_nativeInit(JNIEnv\* env, jclass clazz) {  
    NativeMessageQueue\* nativeMessageQueue = new NativeMessageQueue();  
    if (!nativeMessageQueue) {  
        jniThrowRuntimeException(env, "Unable to allocate native queue");  
        return 0;  
    }  
  
    nativeMessageQueue->incStrong(env);  
    return reinterpret\_cast<jlong>(nativeMessageQueue);  
}  



很簡單,創建一個Native層的消息隊列,如果創建失敗,拋異常信息,返回0,否則將指針轉換為Java的long型值返回。當然,會被Java層的MQ所持有。

NativeMessageQueue 類的構造函數



NativeMessageQueue::NativeMessageQueue() :  
        mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {  
    mLooper = Looper::getForThread();  
    if (mLooper == NULL) {  
        mLooper = new Looper(false);  
        Looper::setForThread(mLooper);  
    }  
}  



這裡的Looper是native層Looper,通過靜態方法 Looper::getForThread() 獲取對象實例,如果未獲取到,則創建實例,並通過靜態方法設置。

看一下Java層MQ中會使用到的native方法



class MessageQueue {  
    private long mPtr; // used by native code  
  
    private native static long nativeInit();  
  
    private native static void nativeDestroy(long ptr);  
  
    private native void nativePollOnce(long ptr, int timeoutMillis); /\*non-static for callbacks\*/  
  
    private native static void nativeWake(long ptr);  
  
    private native static boolean nativeIsPolling(long ptr);  
  
    private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);  
}  



對應簽名:



static const JNINativeMethod gMessageQueueMethods\[\] = {  
    /\* name, signature, funcPtr \*/  
    { "nativeInit", "()J", (void\*)android\_os\_MessageQueue\_nativeInit },  
    { "nativeDestroy", "(J)V", (void\*)android\_os\_MessageQueue\_nativeDestroy },  
    { "nativePollOnce", "(JI)V", (void\*)android\_os\_MessageQueue\_nativePollOnce },  
    { "nativeWake", "(J)V", (void\*)android\_os\_MessageQueue\_nativeWake },  
    { "nativeIsPolling", "(J)Z", (void\*)android\_os\_MessageQueue\_nativeIsPolling },  
    { "nativeSetFileDescriptorEvents", "(JII)V",  
            (void\*)android\_os\_MessageQueue\_nativeSetFileDescriptorEvents },  
};  



mPtr 是Native層MQ的記憶體地址在Java層的映射。

  • Java層判斷MQ是否還在工作:



private boolean isPollingLocked() {  
    // If the loop is quitting then it must not be idling.  
    // We can assume mPtr != 0 when mQuitting is false.  
    return !mQuitting && nativeIsPolling(mPtr);  
}  





static jboolean android\_os\_MessageQueue\_nativeIsPolling(JNIEnv\* env, jclass clazz, jlong ptr) {  
    NativeMessageQueue\* nativeMessageQueue = reinterpret\_cast<NativeMessageQueue\*>(ptr);  
    return nativeMessageQueue->getLooper()->isPolling();  
}  





/\*\*  
 \* Returns whether this looper's thread is currently polling for more work to do.  
 \* This is a good signal that the loop is still alive rather than being stuck  
 \* handling a callback.  Note that this method is intrinsically racy, since the  
 \* state of the loop can change before you get the result back.  
 \*/  
bool isPolling() const;  



  • 喚醒 Native層MQ:



static void android\_os\_MessageQueue\_nativeWake(JNIEnv\* env, jclass clazz, jlong ptr) {  
    NativeMessageQueue\* nativeMessageQueue = reinterpret\_cast<NativeMessageQueue\*>(ptr);  
    nativeMessageQueue->wake();  
}  
  
void NativeMessageQueue::wake() {  
    mLooper->wake();  
}  



  • Native層Poll:



static void android\_os\_MessageQueue\_nativePollOnce(JNIEnv\* env, jobject obj,  
        jlong ptr, jint timeoutMillis) {  
    NativeMessageQueue\* nativeMessageQueue = reinterpret\_cast<NativeMessageQueue\*>(ptr);  
    nativeMessageQueue->pollOnce(env, obj, timeoutMillis);  
}  
  
void NativeMessageQueue::pollOnce(JNIEnv\* env, jobject pollObj, int timeoutMillis) {  
    mPollEnv = env;  
    mPollObj = pollObj;  
    mLooper->pollOnce(timeoutMillis);  
    mPollObj = NULL;  
    mPollEnv = NULL;  
  
    if (mExceptionObj) {  
        env->Throw(mExceptionObj);  
        env->DeleteLocalRef(mExceptionObj);  
        mExceptionObj = NULL;  
    }  
}  



這裡比較重要,我們先大概看下 Native層的Looper是 如何分發消息



//Looper.h  
  
int pollOnce(int timeoutMillis, int\* outFd, int\* outEvents, void\*\* outData);  
inline int pollOnce(int timeoutMillis) {  
    return pollOnce(timeoutMillis, NULL, NULL, NULL);  
}  
  
//實現  
  
int Looper::pollOnce(int timeoutMillis, int\* outFd, int\* outEvents, void\*\* outData) {  
    int result = 0;  
    for (;;) {  
        while (mResponseIndex < mResponses.size()) {  
            const Response& response = mResponses.itemAt(mResponseIndex++);  
            int ident = response.request.ident;  
            if (ident >= 0) {  
                int fd = response.request.fd;  
                int events = response.events;  
                void\* data = response.request.data;  
#if DEBUG\_POLL\_AND\_WAKE  
                ALOGD("%p ~ pollOnce - returning signalled identifier %d: "  
                        "fd=%d, events=0x%x, data=%p",  
                        this, ident, fd, events, data);  
#endif  
                if (outFd != NULL) \*outFd = fd;  
                if (outEvents != NULL) \*outEvents = events;  
                if (outData != NULL) \*outData = data;  
                return ident;  
            }  
        }  
  
        if (result != 0) {  
#if DEBUG\_POLL\_AND\_WAKE  
            ALOGD("%p ~ pollOnce - returning result %d", this, result);  
#endif  
            if (outFd != NULL) \*outFd = 0;  
            if (outEvents != NULL) \*outEvents = 0;  
            if (outData != NULL) \*outData = NULL;  
            return result;  
        }  
  
        result = pollInner(timeoutMillis);  
    }  
}  



先處理Native層滯留的Response,然後調用pollInner。這裡的細節比較複雜,稍後我們在 Native Looper解析 中進行腦暴。

先於此處細節分析,我們知道,調用一個方法,這是阻塞的 ,用大白話描述即在方法返回前,調用者在 等待。

Java層調動 native void nativePollOnce(long ptr, int timeoutMillis); 過程中是阻塞的。

此時我們再閱讀下Java層MQ的消息獲取:代碼比較長,直接在代碼中進行要點註釋。

在看之前,我們先單純從 TDD的角度 思考下,有哪些 主要場景 :當然,這些場景不一定都合乎Android現有的設計

消息隊列是否在工作中

  • 工作中,期望返回消息

  • 不工作,期望返回null

工作中的消息隊列 當前 是否有消息

  • 特殊的 內部功能性消息,期望MQ內部自行處理

  • 已經到處理時間的消息, 返回消息

  • 未到處理時間,如果都是排過序的,期望 空轉保持阻塞 or 返回靜默並設置喚醒?按照前面的討論,是期望 保持空轉

  • 不存在消息,阻塞 or 返回null?-- 如果返回null,則在外部需要需要 保持空轉 或者 喚醒機制,以支持正常運作。從封裝角度出發,應當 保持空轉,自己解決問題

  • 存在消息



class MessageQueue {  
    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.  
        // 1. 如果 native消息隊列指針映射已經為0,即虛引用,說明消息隊列已經退出,沒有消息了。  
        // 則返回 null  
        final long ptr = mPtr;  
        if (ptr == 0) {  
            return null;  
        }  
  
        int pendingIdleHandlerCount = -1; // -1 only during first iteration  
        int nextPollTimeoutMillis = 0;  
  
        // 2. 死迴圈,當為獲取到需要 \`分發處理\` 的消息時,保持空轉  
        for (;;) {  
            if (nextPollTimeoutMillis != 0) {  
                Binder.flushPendingCommands();  
            }  
  
            // 3. 調用native層方法,poll message,註意,消息還存在於native層  
            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;  
  
                //4. 如果發現 barrier ,即同步屏障,則尋找隊列中的下一個可能存在的非同步消息  
                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) {  
                    // 5. 發現了消息,  
                    // 如果是還沒有到約定時間的消息,則設置一個 \`下次喚醒\` 的最大時間差  
                    // 否則 \`維護單鏈表信息\` 並返回消息  
  
                    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 (DEBUG) Log.v(TAG, "Returning message: " + msg);  
                        msg.markInUse();  
                        return msg;  
                    }  
                } else {  
                    // No more messages.  
                    nextPollTimeoutMillis = -1;  
                }  
  
                // 處理 是否需要 停止消息隊列                  
                // Process the quit message now that all pending messages have been handled.  
                if (mQuitting) {  
                    dispose();  
                    return null;  
                }  
  
                // 維護 接下來需要處理的 IDLEHandler 信息,  
                // 如果沒有 IDLEHandler,則直接進入下一輪消息獲取環節  
                // 否則處理 IDLEHandler  
                // 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;  
                }  
  
                if (mPendingIdleHandlers == null) {  
                    mPendingIdleHandlers = new IdleHandler\[Math.max(pendingIdleHandlerCount, 4)\];  
                }  
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);  
            }  
  
            // 處理 IDLEHandler  
            // Run the idle handlers.  
            // We only ever reach this code block during the first iteration.  
            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;  
        }  
    }  
}  



  • Java層壓入消息

這就比較簡單了,當消息本身合法,且消息隊列還在工作中時。依舊從 TDD角度 出發:

如果消息隊列沒有頭,期望直接作為頭

如果有頭

  • 消息處理時間 先於 頭消息 或者是需要立即處理的消息,則作為新的頭

  • 否則按照 處理時間 插入到合適位置



 boolean enqueueMessage(Message msg, long when) {  
        if (msg.target == null) {  
            throw new IllegalArgumentException("Message must have a target.");  
        }  
  
        synchronized (this) {  
            if (msg.isInUse()) {  
                throw new IllegalStateException(msg + " This message is already in use.");  
            }  
  
            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;  
            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;  
    }


同步屏障 barrier後面單獨腦暴, 其他部分就先不看了

Java層消息分發

這一節開始,我們腦暴消息分發,前面我們已經看過了 MessageQueue ,消息分發就是 不停地 從 MessageQueue 中取出消息,並指派給處理者。 完成這一工作的,是Looper。

在前面,我們已經知道了,Native層也有Looper,但是不難理解:

  • 消息隊列需要 橋梁 連通 Java層和Native層

  • Looper只需要 在自己這一端,處理自己的消息隊列分發即可

所以,我們看Java層的消息分發時,看Java層的Looper即可。關註三個主要方法:

  • 出門上班

  • 工作

  • 下班回家

  • 出門上班 prepare



class Looper {  
  
    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));  
    }  
}  



這裡有兩個註意點:

  • 已經出了門,除非再進門,否則沒法再出門了。同樣,一個線程有一個Looper就夠了,只要它還活著,就沒必要再建一個。

  • 責任到人,一個Looper服務於一個Thread,這需要 註冊 ,代表著 某個Thread 已經由自己服務了。利用了ThreadLocal,因為多線程訪問集合,總需要考慮

競爭,這很不人道主義,乾脆分家,每個Thread操作自己的內容互不幹擾,也就沒有了競爭,於是封裝了 ThreadLocal

  • 上班 loop

註意工作性質是 分發,並不需要自己處理

  • 沒有 註冊 自然就找不到負責這份工作的人。

  • 已經在工作了就不要催,催了會導致工作出錯,順序出現問題。

  • 工作就是不斷的取出 老闆-- MQ 的 指令 -- Message,並交給 相關負責人 -- Handler 去處理,並記錄信息

  • 007,不眠不休,當MQ再也不發出消息了,沒活幹了,大家都散了吧,下班回家



class Looper {  
    public static void loop() {  
        final Looper me = myLooper();  
        if (me == null) {  
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
        }  
        if (me.mInLoop) {  
            Slog.w(TAG, "Loop again would have the queued messages be executed"  
                    + " before this one completed.");  
        }  
  
        me.mInLoop = true;  
        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();  
  
        // Allow overriding a threshold with a system prop. e.g.  
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'  
        final int thresholdOverride =  
                SystemProperties.getInt("log.looper."  
                        + Process.myUid() + "."  
                        + Thread.currentThread().getName()  
                        + ".slow", 0);  
  
        boolean slowDeliveryDetected = false;  
  
        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);  
            }  
            // Make sure the observer won't change while processing a transaction.  
            final Observer observer = sObserver;  
  
            final long traceTag = me.mTraceTag;  
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;  
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;  
            if (thresholdOverride > 0) {  
                slowDispatchThresholdMs = thresholdOverride;  
                slowDeliveryThresholdMs = thresholdOverride;  
            }  
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);  
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);  
  
            final boolean needStartTime = logSlowDelivery || logSlowDispatch;  
            final boolean needEndTime = logSlowDispatch;  
  
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {  
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));  
            }  
  
            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;  
            final long dispatchEnd;  
            Object token = null;  
            if (observer != null) {  
                token = observer.messageDispatchStarting();  
            }  
            long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);  
            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);  
                }  
            }  
            if (logSlowDelivery) {  
                if (slowDeliveryDetected) {  
                    if ((dispatchStart - msg.when) <= 10) {  
                        Slog.w(TAG, "Drained");  
                        slowDeliveryDetected = false;  
                    }  
                } else {  
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",  
                            msg)) {  
                        // Once we write a slow delivery log, suppress until the queue drains.  
                        slowDeliveryDetected = true;  
                    }  
                }  
            }  
            if (logSlowDispatch) {  
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);  
            }  
  
            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();  
        }  
    }  
}  



  • 下班 quit/quitSafely

這是比較粗暴的行為,MQ離開了Looper就沒法正常工作了,即下班即意味著辭職



class Looper {  
    public void quit() {  
        mQueue.quit(false);  
    }  
  
    public void quitSafely() {  
        mQueue.quit(true);  
    }  
}  



/ Handler /

這裡就比較清晰了。API基本分為以下幾類:

  • 面向使用者:

  • 創建Message,通過Message的 享元模式

  • 發送消息,註意postRunnable也是一個消息

  • 移除消息,

  • 退出等

面向消息處理:



class Handler {  
    /\*\*  
     \* Subclasses must implement this to receive messages.  
     \*/  
    public void handleMessage(@NonNull Message msg) {  
    }  
  
    /\*\*  
     \* Handle system messages here.  
     \* Looper分發時調用的API  
     \*/  
    public void dispatchMessage(@NonNull Message msg) {  
        if (msg.callback != null) {  
            handleCallback(msg);  
        } else {  
            if (mCallback != null) {  
                if (mCallback.handleMessage(msg)) {  
                    return;  
                }  
            }  
            handleMessage(msg);  
        }  
    }  
}  



如果有 Handler callback,則交給callback處理,否則自己處理,如果沒覆寫 handleMessage ,消息相當於被 drop 了。

消息發送部分可以結合下圖梳理:

階段性小結,至此,我們已經對 Framework層的消息機制 有一個完整的瞭解了。 前面我們梳理了:

  • Native層 和 Java層均有消息隊列,並且通過JNI和指針映射,存在對應關係

  • Native層 和 Java層MQ 消息獲取時的大致過程

  • Java層 Looper 如何工作

  • Java層 Handler 大致概覽

根據前面梳理的內容,可以總結:從 Java Runtime 看:

  • 消息隊列機制服務於 線程級別,即一個線程有一個工作中的消息隊列即可,當然,也可以沒有。

  • 即,一個Thread 至多有 一個工作中的Looper。

  • Looper 和 Java層MQ 一一對應

  • Handler 是MQ的入口,也是 消息 的處理者

  • 消息-- Message 應用了 享元模式,自身信息足夠,滿足 自洽,創建消息的開銷性對較大,所以利用享元模式對消息對象進行復用。

下麵我們再繼續探究細節,解決前面語焉不詳處留下的疑惑:

  • 消息的類型和本質

  • Native層Looper 的pollInner

類型和本質

message中的幾個重要成員變數:



class Message {  
  
    public int what;  
  
    public int arg1;  
  
    public int arg2;  
  
    public Object obj;  
  
    public Messenger replyTo;  
  
    /\*package\*/ int flags;  
  
    public long when;  
  
    /\*package\*/ Bundle data;  
  
    /\*package\*/ Handler target;  
  
    /\*package\*/ Runnable callback;  
  
}  



其中 target是 目標,如果沒有目標,那就是一個特殊的消息: 同步屏障 即 barrier;

what 是消息標識 arg1 和 arg2 是開銷較小的 數據,如果 不足以表達信息 則可以放入 Bundle data 中。

replyTo 和 obj 是跨進程傳遞消息時使用的,暫且不看。

flags 是 message 的狀態標識,例如 是否在使用中,是否是同步消息

上面提到的同步屏障,即 barrier,其作用是攔截後面的 同步消息 不被獲取,在前面閱讀Java層MQ的next方法時讀到過。

我們還記得,next方法中,使用死迴圈,嘗試讀出一個滿足處理條件的消息,如果取不到,因為死迴圈的存在,調用者(Looper)會被一直阻塞。

此時可以印證一個結論,消息按照 功能分類 可以分為 三種:

  • 普通消息

  • 同步屏障消息

  • 非同步消息

其中同步消息是一種內部機制。設置屏障之後需要在合適時間取消屏障,否則會導致 普通消息永遠無法被處理,而取消時,需要用到設置屏障時返回的token。

Native層Looper

相信大家都對 Native層 的Looper產生興趣了,想看看它在Native層都幹些什麼。

對完整源碼感興趣的可以看 這裡(https://github.com/leobert-lan/Blog/blob/main/Android/Mechanism/Message/code/Looper.cpp) ,下麵我們節選部分進行閱讀。

前面提到了Looper的pollOnce,處理完擱置的Response之後,會調用pollInner獲取消息



int Looper::pollInner(int timeoutMillis) {  
#if DEBUG\_POLL\_AND\_WAKE  
    ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);  
#endif  
  
    // Adjust the timeout based on when the next message is due.  
    if (timeoutMillis != 0 && mNextMessageUptime != LLONG\_MAX) {  
        nsecs\_t now = systemTime(SYSTEM\_TIME\_MONOTONIC);  
        int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);  
        if (messageTimeoutMillis >= 0  
                && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {  
            timeoutMillis = messageTimeoutMillis;  
        }  
#if DEBUG\_POLL\_AND\_WAKE  
        ALOGD("%p ~ pollOnce - next message in %lldns, adjusted timeout: timeoutMillis=%d",  
                this, mNextMessageUptime - now, timeoutMillis);  
#endif  
    }  
  
    // Poll.  
    int result = ALOOPER\_POLL\_WAKE;  
    mResponses.clear();  
    mResponseIndex = 0;  
  
    struct epoll\_event eventItems\[EPOLL\_MAX\_EVENTS\];  
  
    //註意 1  
    int eventCount = epoll\_wait(mEpollFd, eventItems, EPOLL\_MAX\_EVENTS, timeoutMillis);  
  
    // Acquire lock.  
    mLock.lock();  
  
// 註意 2  
    // Check for poll error.  
    if (eventCount < 0) {  
        if (errno == EINTR) {  
            goto Done;  
        }  
        ALOGW("Poll failed with an unexpected error, errno=%d", errno);  
        result = ALOOPER\_POLL\_ERROR;  
        goto Done;  
    }  
  
// 註意 3  
    // Check for poll timeout.  
    if (eventCount == 0) {  
#if DEBUG\_POLL\_AND\_WAKE  
        ALOGD("%p ~ pollOnce - timeout", this);  
#endif  
        result = ALOOPER\_POLL\_TIMEOUT;  
        goto Done;  
    }  
  
//註意 4  
    // Handle all events.  
#if DEBUG\_POLL\_AND\_WAKE  
    ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);  
#endif  
  
    for (int i = 0; i < eventCount; i++) {  
        int fd = eventItems\[i\].data.fd;  
        uint32\_t epollEvents = eventItems\[i\].events;  
        if (fd == mWakeReadPipeFd) {  
            if (epollEvents & EPOLLIN) {  
                awoken();  
            } else {  
                ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);  
            }  
        } else {  
            ssize\_t requestIndex = mRequests.indexOfKey(fd);  
            if (requestIndex >= 0) {  
                int events = 0;  
                if (epollEvents & EPOLLIN) events |= ALOOPER\_EVENT\_INPUT;  
                if (epollEvents & EPOLLOUT) events |= ALOOPER\_EVENT\_OUTPUT;  
                if (epollEvents & EPOLLERR) events |= ALOOPER\_EVENT\_ERROR;  
                if (epollEvents & EPOLLHUP) events |= ALOOPER\_EVENT\_HANGUP;  
                pushResponse(events, mRequests.valueAt(requestIndex));  
            } else {  
                ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "  
                        "no longer registered.", epollEvents, fd);  
            }  
        }  
    }  
Done: ;  
  
// 註意 5  
    // Invoke pending message callbacks.  
    mNextMessageUptime = LLONG\_MAX;  
    while (mMessageEnvelopes.size() != 0) {  
        nsecs\_t now = systemTime(SYSTEM\_TIME\_MONOTONIC);  
        const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);  
        if (messageEnvelope.uptime <= now) {  
            // Remove the envelope from the list.  
            // We keep a strong reference to the handler until the call to handleMessage  
            // finishes.  Then we drop it so that the handler can be deleted \*before\*  
            // we reacquire our lock.  
            { // obtain handler  
                sp<MessageHandler> handler = messageEnvelope.handler;  
                Message message = messageEnvelope.message;  
                mMessageEnvelopes.removeAt(0);  
                mSendingMessage = true;  
                mLock.unlock();  
  
#if DEBUG\_POLL\_AND\_WAKE || DEBUG\_CALLBACKS  
                ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",  
                        this, handler.get(), message.what);  
#endif  
                handler->handleMessage(message);  
            } // release handler  
  
            mLock.lock();  
            mSendingMessage = false;  
            result = ALOOPER\_POLL\_CALLBACK;  
        } else {  
            // The last message left at the head of the queue determines the next wakeup time.  
            mNextMessageUptime = messageEnvelope.uptime;  
            break;  
        }  
    }  
  
    // Release lock.  
    mLock.unlock();  
  
//註意 6  
    // Invoke all response callbacks.  
    for (size\_t i = 0; i < mResponses.size(); i++) {  
        Response& response = mResponses.editItemAt(i);  
        if (response.request.ident == ALOOPER\_POLL\_CALLBACK) {  
            int fd = response.request.fd;  
            int events = response.events;  
            void\* data = response.request.data;  
#if DEBUG\_POLL\_AND\_WAKE || DEBUG\_CALLBACKS  
            ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",  
                    this, response.request.callback.get(), fd, events, data);  
#endif  
            int callbackResult = response.request.callback->handleEvent(fd, events, data);  
            if (callbackResult == 0) {  
                removeFd(fd);  
            }  
            // Clear the callback reference in the response structure promptly because we  
            // will not clear the response vector itself until the next poll.  
            response.request.callback.clear();  
            result = ALOOPER\_POLL\_CALLBACK;  
        }  
    }  
    return result;  
}  



上面標記了註意點

  • 1 epoll機制,等待 mEpollFd 產生事件, 這個等待具有超時時間。

  • 2,3,4 是等待的三種結果,goto 語句可以直接跳轉到 標記 處

  • 2 檢測poll 是否出錯,如果有,跳轉到 Done

  • 3 檢測pool 是否超時,如果有,跳轉到 Done

  • 4 處理epoll後所有的事件

  • 5 處理 pending 消息的回調

  • 6 處理 所有 Response的回調

並且我們可以發現返回的結果有以下幾種:

  • ALOOPER_POLL_CALLBACK

有 pending message 或者 request.ident 值為 ALOOPER_POLL_CALLBACK 的 Response被處理了。 如果沒有:

  • ALOOPER_POLL_WAKE 正常喚醒

  • ALOOPER_POLL_ERROR epoll錯誤

  • ALOOPER_POLL_TIMEOUT epoll超時

查找了一下枚舉值:



ALOOPER\_POLL\_WAKE = -1,  
ALOOPER\_POLL\_CALLBACK = -2,  
ALOOPER\_POLL\_TIMEOUT = -3,  
ALOOPER\_POLL\_ERROR = -4  



階段性小結, 我們對 消息 和 Native層的pollInner 進行了一次腦暴,引出了epoll機制。

其實Native層的 Looper分發還有不少值得腦暴的點,但我們先緩緩,已經迫不及待的要對 epoll機制進行腦暴了。

腦暴:Linux中的I/O模型

PS:本段中,存在部分圖片直接引用自該文,我偷了個懶,沒有去找原版內容並標記出處

阻塞I/O模型圖:在調用recv()函數時,發生在內核中等待數據和複製數據的過程

實現非常的 簡單,但是存在一個問題,阻塞導致線程無法執行其他任何計算,如果是在網路編程背景下,需要使用多線程提高處理併發的能力。

註意,不要用 Android中的 點擊屏幕等硬體被觸發事件 去對應這裡的 網路併發,這是兩碼事。

如果採用了 多進程 或者 多線程 實現 併發應答,模型如下:

到這裡,我們看的都是 I/O 阻塞 模型。

腦暴,阻塞為調用方法後一直在等待返回值,線程內執行的內容就像 卡頓 在這裡。

如果要消除這種卡頓,那就不能調用方法等待I/O結果,而是要 立即返回 !舉個例子:

  • 去西裝店定製西裝,確定好款式和尺寸後,你坐在店裡一直等著,等到做好了拿給你,這就是阻塞型的,這能等死你;

  • 去西裝店定製西裝,確定好款式和尺寸後,店員告訴你別乾等著,好多天呢,等你有空了來看看,這就是非阻塞型的。

改變為非阻塞模型後,應答模型如下:

不難理解,這種方式需要顧客去 輪詢 。對客戶不友好,但是對店家可是一點損失都沒有,還讓等候區沒那麼擠了。

有些西裝店進行了改革,對客戶更加友好了:

去西裝店定製西裝,確定好款式和尺寸後,留下聯繫方式,等西服做好了聯繫客戶,讓他來取。

這就變成了 select or poll 模型:

註意:進行改革的西裝店需要增加一個員工,圖中標識的用戶線程,他的工作是:

  • 在前臺記錄客戶訂單和聯繫方式

  • 拿記錄著 訂單 的小本子去找製作間,不斷檢查 訂單是否完工,完工的就可以提走並聯繫客戶了。

而且,他去看訂單完工時,無法在前臺記錄客戶信息,這意味他 阻塞 了,其他工作只能先擱置著。

這個做法,對於製作間而言,和 非阻塞模型 並沒有多大區別。還增加了一個店員,但是,用 一個店員 就解決了之前 很多店員 都會跑去 製作間 幫客戶問"訂單好了沒有?" 的問題。

值得一提的是,為了提高服務質量,這個員工每次去製作間詢問一個訂單時,都需要記錄一些信息:

  • 訂單完成度詢問時,是否被應答;

  • 應答有沒有說謊;等

有些店對每種不同的考核項均準備了記錄冊,這和 select模型類似

有些店只用一本記錄冊,但是冊子上可以利用表格記錄各種考核項,這和 poll 模型類似

select 模型 和 poll 模型的近似度比較高。

沒多久,老闆就發現了,這個店員的工作效率有點低下,他每次都要拿著一本訂單簿,去把訂單都問一遍,倒不是員工不勤快,是這個模式有點問題。

於是老闆又進行了改革:

  • 在 前臺 和 製作間 之間加一個送信管道。

  • 製作間有進度需要彙報了,就送一份信到前臺,信上寫著訂單號。

  • 前臺員工直接去問對應的訂單。

這就變成了 epoll模型解決了 select/poll 模型的遍歷效率問題。

這樣改革後,前臺員工就不再需要按著訂單簿從上到下挨個問了。提高了效率,前臺員工只要無事發生,就可以優雅的划水了。

我們看一下NativeLooper的構造函數:



Looper::Looper(bool allowNonCallbacks) :  
        mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),  
        mResponseIndex(0), mNextMessageUptime(LLONG\_MAX) {  
    int wakeFds\[2\];  
    int result = pipe(wakeFds);  
    LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);  
  
    mWakeReadPipeFd = wakeFds\[0\];  
    mWakeWritePipeFd = wakeFds\[1\];  
  
    result = fcntl(mWakeReadPipeFd, F\_SETFL, O\_NONBLOCK);  
    LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",  
            errno);  
  
    result = fcntl(mWakeWritePipeFd, F\_SETFL, O\_NONBLOCK);  
    LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",  
            errno);  
  
    // Allocate the epoll instance and register the wake pipe.  
    mEpollFd = epoll\_create(EPOLL\_SIZE\_HINT);  
    LOG\_ALWAYS\_FATAL\_IF(mEpollFd < 0, "Could not create epoll instance.  errno=%d", errno);  
  
    struct epoll\_event eventItem;  
    memset(& eventItem, 0, sizeof(epoll\_event)); // zero out unused members of data field union  
    eventItem.events = EPOLLIN;  
    eventItem.data.fd = mWakeReadPipeFd;  
    result = epoll\_ctl(mEpollFd, EPOLL\_CTL\_ADD, mWakeReadPipeFd, & eventItem);  
    LOG\_ALWAYS\_FATAL\_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",  
            errno);  
}  



總結

相信看到這裡,大家已經自己悟透了各種問題。按照慣例,還是要總結下,因為 這篇是腦暴,所以 思緒 是比較 跳躍 的,內容前後關係不太明顯。

我們結合一個問題來點明內容前後關係。

Java層 Looper和MQ 會什麼使用了死迴圈但是 不會"阻塞"UI線程 / 沒造成ANR / 依舊可以響應點擊事件

  • Android是基於 事件驅動 的,並建立了 完善的 消息機制

  • Java層的消息機制只是一個局部,其負責的就是面向消息隊列,處理 消息隊列管理,消息分發,消息處理

  • Looper的死迴圈保障了 消息隊列 的 消息分發 一直處於有效運行中,不迴圈就停止了分發。

  • MessageQueue的 死迴圈 保障了 Looper可以獲取有效的消息,保障了Looper 只要有消息,就一直運行,發現有效消息,就跳出了死迴圈。

  • 而且Java層MessageQueue在 next() 方法中的死迴圈中,通過JNI調用了 Native層MQ的 pollOnce,驅動了Native層去處理Native層消息

  • 值得一提的是,UI線程處理的事情也都是基於消息的,無論是更新UI還是響應點擊事件等。

所以,正是Looper 進行loop()之後的死迴圈,保障了UI線程的各項工作正常執行。

再說的ANR,這是Android 確認主線程 消息機制 正常 且 健康 運轉的一種檢測機制。

因為主線程Looper需要利用 消息機制 驅動UI渲染和交互事件處理, 如果某個消息的執行,或者其衍生出的業務,在主線程占用了大量的時間,導致主線程長期阻塞,會影響用戶體驗。

所以ANR檢測採用了一種 埋定時炸彈 的機制,必須依靠Looper的高效運轉來消除之前裝的定時炸彈。而這種定時炸彈比較有意思,被髮現了才會炸。

在說到 響應點擊事件,類似的事件總是從硬體出發的,在到內核,再進程間通信到用戶空間,這些事件以消息的形式存在於Native層,經過處理後,表現出:

ViewRootImpl收到了InputManager的輸入,併進行了事件處理

這裡我們借用一張圖總結整個消息機制流程:

最後,喜歡的朋友可以點個關註,覺得本文不錯的朋友可以點個贊,你的支持就是我更新最大的動力。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 一、環境準備 1、鏡像包 CentOS-7.9-x86_64-DVD-2009.iso ubuntu-18.04.6-server-amd64.iso 2、VMware 二、鏡像下載 阿裡雲:developer.aliyun.com/mirror ...
  • 解決過程 在使用stm32H743+外置USB2.0高速phy(smsc USB3343)過程中,發現設備無法被枚舉為hs模式,而是一直被枚舉為fs。測試速度,如下: 16:24:24.672288:開始測試單片機向上位機發送數據…… 16:24:25.671740:結束測試,速度約為 831.48 ...
  • 在我們日常工作中,為了驗證開發的功能,比如:文件上傳功能或者演算法的處理效率等,經常需要一些大文件進行測試,有時在四處找了一頓之後,發現竟然沒有一個合適的,雖然 Linux 中也有一些命令比如:vim、touch 等可以創建文件,但是如果需要一個 100G 或者 1T 的大文件,這些命令就顯得力不從心 ...
  • 1、指針函數 指針函數,從名字上看它本質上是一個函數。指針函數:返回值類型是指針的函數。函數聲明如下: int *plusfunction(int a,int b); 當然也可以寫成如下格式: int* plusfunction(int a,int b); 讓指針標誌 * 與int緊貼在一起,而與函 ...
  • 什麼雲主機既能隨時自助獲取、可彈性伸縮,價格還不貴,一年只要39元,那必定就是華為雲主機,因為其好的售後體驗,華為雲獲得可信雲電商雲服務獎,雲主機獲五星+最高評級。下麵我們來瞭解下華為雲主機吧。 華為云云主機介紹 華為云云主機是一種彈性雲伺服器(Elastic Cloud Server, ECS), ...
  • 企業雲伺服器怎麼選,要安全、靈活,還有容量大,可以試試這款華為云云主機,華為的技術一直是國內天花板級別的,所以你可以相信華為云云主機的性能。下麵對此做個評測: 企業在選擇華為雲主機遇到的問題: 很多企業會在多個雲平臺部署業務,一來享受不同雲廠商的產品和服務優勢;二來分散和減少業務系統風險。但多雲部署 ...
  • 雲主機作為雲計算最基礎、最核心的產品,承擔了大部分企業的計算任務,其性能和穩定性直接決定了雲計算的用戶體驗。 眾所周知,雲計算從來不是科技的狂人妄語,在科技技術飛速發展的時代,在技術市場,我們目睹了這個產業從零到數千億美元,黃金白銀的背後都來自產業的真實需求。尤其是突如其來的疫情,雖然讓很多產業均受 ...
  • Linux進程通訊機制 Linux 系統中有萬物皆文件的說法,虛擬文件系統(VFS)是 Linux 對外的介面,任何程式都必須通過這層介面來使用它。 為了避免系統安全問題(越權訪問),進程間記憶體無法共用,數據交互就得採用特殊的通信機制(IPC)。 進程劃分用戶空間(不可共用)跟內核空間(可共用),並 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...