준비 ☞ Android 비동기 메시지 배포 메커니즘

14660 단어
Android 메시지 메커니즘
– 주로 Handler 의 운영 체제 와 Message Queue, looper 의 작업 과정 을 말한다.
  • Message Queue Message Queue 메시지 큐 는 메 시 지 를 저장 하 는 데 사 용 됩 니 다. 메시지 큐 라 고 하지만 저장 구 조 는 단일 체인 표 의 데이터 구조 로 메시지 큐 를 저장 합 니 다.두 동작 삽입 (enqueueMessage) 과 읽 기 (next) enqueueMessage 를 포함 합 니 다. 메시지 링크 에 메시지 next 를 삽입 합 니 다. 메시지 목록 에서 하루 메 시 지 를 읽 고 메시지 큐 에서 제거 합 니 다. next 방법 은 무한 순환 방법 입 니 다. 메시지 목록 에 메시지 가 없 으 면 계속 막 힙 니 다.
  • Looper Looper 메시지 순환, 메 시 지 를 처리 합 니 다.Looper 는 끊임없이 Message Queue 에서 새로운 메시지 가 있 는 지 확인 하고 새로운 메시지 가 있 으 면 즉시 처리 합 니 다
  • Looper.java
    
    private Looper(boolean quitAllowed) {
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
        }
    

    Looper 의 구조 방법 은 메시지 큐, 메시지 큐 를 만 든 다음 현재 스 레 드 의 대상 을 저장 합 니 다.
    
    public static @Nullable Looper myLooper() {
            return sThreadLocal.get();
        }
    
    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. prepare () 가 두 번 호출 되 지 않 습 니까?
     :       Looper.prepare()          ThreadLocal          Looper   ,            。
     /**
         * Run the message queue in this thread. Be sure to call
         * {@link #quit()} to end the 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.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
                final 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);
                } 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 방법 은 사 순환 입 니 다. 사 순환 에서 벗 어 나 는 방법 입 니 다. Message Queue 의 Next 방법 이 비어 있 습 니 다. 즉, quue. next () 가 비어 있 습 니 다.Looper 는 quit 방법 이나 quitSafely 방법 을 호출 하여 메시지 대기 열 이 종료 되 었 음 을 알 리 고 Message Queue 의 next 방법 을 비 워 줍 니 다.
    loop 은 Message Queue 의 next 방법 으로 새로운 정 보 를 얻 습 니 다. 메시지 가 없 으 면 next 방법 이 계속 막 혀 서 loop 방법 도 계속 막 힐 것 입 니 다.next 방법 이 새로운 메 시 지 를 되 돌려 주면 Looper 는 새로운 메 시 지 를 처리 하고 msg. target. dispatchMessage (msg) 를 호출 합 니 다. msg. target 은 이 메 시 지 를 보 낸 Handler 대상 (Handler 에 설명 이 있 습 니 다) 입 니 다.이렇게 해서 코드 논 리 를 지정 한 스 레 드 로 전환 하여 실행 합 니 다.3. ThreadLocal
    스 레 드 내부 의 데이터 저장 류 는 지정 한 스 레 드 에 데 이 터 를 저장 할 수 있 고 저장 한 후에 지정 한 스 레 드 에서 만 저 장 된 데 이 터 를 가 져 올 수 있 으 며 다른 스 레 드 는 가 져 올 수 없습니다.응용: 일부 데이터 가 스 레 드 를 역할 영역 으로 하고 서로 다른 스 레 드 가 서로 다른 데 이 터 를 가지 고 Looper 에 존재 할 때 스 레 드 가 아니 라 모든 스 레 드 에 데 이 터 를 저장 하 는 역할 을 합 니 다.
    질문: Handler 내 부 는 현재 스 레 드 의 Looper 를 어떻게 가 져 옵 니까?
    Handler.java
    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());
                }
            }
            mLooper = Looper.myLooper();
            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;
        }

    답: Handler 는 ThreadLocal 을 통 해 모든 스 레 드 의 Looper 를 가 져 옵 니 다. ThreadLocal 은 서로 다른 스 레 드 에서 서로 간섭 하지 않 고 저장 하고 데 이 터 를 제공 할 수 있 습 니 다.Looper. prepare () 를 호출 할 때 "sThreadLocal. set (new Looper (quitAllowed)"; - Looper 인 스 턴 스 를 만 들 고 Looper 인 스 턴 스 를 ThreadLocal 저장 소 에 넣 었 습 니 다.그리고 Handler 에서 "mLooper = Looper. my Looper ();" - sThreadLocal. get () 에서 Looper 대상 을 가 져 옵 니 다.
    질문: 메 인 스 레 드 에서 왜 Handler 를 기본 으로 사용 할 수 있 습 니까?
    답: 스 레 드 는 기본적으로 Looper 가 없습니다. Handler 를 사용 하려 면 스 레 드 에 Looper 를 만들어 야 합 니 다. 그러나 주 스 레 드, 즉 UI 스 레 드 는 Activity Thread 입 니 다. Activity Thread 가 생 성 될 때 기본적으로 Looper 를 초기 화 합 니 다. 현재 UI 스 레 드 는 Looper. prepare () 와 Looper. loop () 방법 을 호출 합 니 다. 4. Handler 주요 작업: 메 시 지 를 보 내 고 받 습 니 다.
     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("Looper", 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 가 메 시 지 를 보 내 는 과정 은 메시지 링크 에 메 시 지 를 삽입 하 는 것 입 니 다. Message Queue 의 next 방법 은 이 메 시 지 를 Looper 에 게 되 돌려 주 고 Looper 는 메 시 지 를 받 으 며 msg. target. dispatchMessage (msg) 를 통 해 Handler 에 게 전달 합 니 다.위의 enqueueMessage 방법 은 먼저 "msg. target = this;" 를 msg. target 에 할당 합 니 다. 즉, Handler 를 msg 의 target 속성 에 할당 합 니 다.
        public void dispatchMessage(Message msg) {
            if (msg.callback != null) {
                handleCallback(msg);
            } else {
                if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                handleMessage(msg);
            }
        }

    먼저 Message 의 callback 이 null 인지 확인 하고 비어 있 지 않 으 면 handle Callback 을 통 해 메 시 지 를 처리 합 니 다.callback 은 Runnable 인터페이스 로 Handler 의 post 방법 으로 전달 하 는 Runnable 인자 입 니 다.
    private static void handleCallback(Message message) {
            message.callback.run();
        }

    밤 을 들 어 첫 번 째 handler 사용법, post 방법
    Handler mHandler = new handler();
    mHandler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    Log.e("TAG", Thread.currentThread().getName());
                    mTxt.setText("yoxi");
                }
            });

    그 다음 에 mCallback 이 비어 있 는 지, mCallback 은 인터페이스 입 니 다.
        public interface Callback {
            public boolean handleMessage(Message msg);
        }

    Callback 은 Handler 의 하위 클래스 를 파생 하지 않 으 려 면 Callback 을 통 해 구현 할 수 있 는 또 다른 Handler 사용 방식 을 제공한다.밤 을 들 고 두 번 째 는 Handler 를 사용 하 는 방식 입 니 다.
    private Handler mHandler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                switch (msg.what)
                {
                case value:
                    break;
                default:
                    break;
                }
            };
        };

    마지막 으로 Handler 의 handle Message 방법 으로 메 시 지 를 처리 합 니 다.

    좋은 웹페이지 즐겨찾기