Android高級-架構師-Handler Message源碼分析及手寫實現1

我們都用過Handler,也知道handler有兩種使用方式,

目錄

* 1、Handler內存泄露測試
* 2、爲什麼不能在子線程創建Handler
* 3、textView.setText()只能在主線程執行,這句話是錯誤!
* 4、new Handler()兩種寫法有什麼區別?
* 5、ThreadLocal用法和原理

1:實現方式

1:第一種

    private Handler handler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            startActivity(new Intent(MainActivity.this, PersonalActivity.class));
            return false;
        }
    });

第二種

    // 這是谷歌備胎的api,不推薦使用
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            textView.setText(msg.obj.toString());
        }
    };

2:內存泄露問題

摧毀activity

    private void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                                // 1、Handler內存泄露測試(假象)
                SystemClock.sleep(1000); // 銷燬Activity  線程休眠
                Message message = new Message();
                message.what=3;
                handler1.sendMessage(message);
//        
                
            }
        }).start();
    }

雖然打印了activity 的ondestory()方法,還是繼續了跳轉的動作。

所以我們需要在onDestory中

   @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("NetEase ", "onDestroy");

         handler1.removeMessages(3);
        handler1 = null;
    }

如果handler不置爲空,還是會跳轉,如果置空以後就可以了。

3:爲什麼不能在子線程中創建handler

如果我們這樣寫

   private void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                new Handler();

            }
        }).start();
    }
01-02 07:31:06.201 27860-27882/com.netease.handler.sample E/AndroidRuntime: FATAL EXCEPTION: Thread-2
                                                                            Process: com.netease.handler.sample, PID: 27860
                                                                            java.lang.RuntimeException: Can't create handler inside thread Thread[Thread-2,5,main] that has not called Looper.prepare()
                                                                                at android.os.Handler.<init>(Handler.java:207)
                                                                                at android.os.Handler.<init>(Handler.java:119)
                                                                                at com.netease.handler.sample.MainActivity$3.run(MainActivity.java:60)
                                                                                at java.lang.Thread.run(Thread.java:919)

爲什麼會報這個錯呢?因爲app啓動時通過AcitivityThread的main()爲程序入口,

  public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

      //重點看這個方法
        Looper.prepareMainLooper();
   /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
    //追蹤這個方法
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

繼續追蹤

   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是主線程的Looper,這個sThreadLocal是存在ThreadLocalMap中,

比如set方法

   public void set(T value) {
        Thread t = Thread.currentThread();
//這個map集合,new完的Looper放到了Map中,key爲當前的Thread
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

然後我們再看new Handler方法,

   */
    public Handler() {
        this(null, false);
    }
   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());
            }
        }

//在創建Handler中會去取一個myLooper()
        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;
    }

他是直接去map中去取 

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

因爲程序啓動的時候是通過主線程爲key,放入了一個looper,現在用子線程爲key去取looper,勘定取不到,所以纔會報異常。

4:TextView.setTextView只能在主線程執行嗎?我們試一下

 

  private void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                textView.setText("我在測試~~~~");

            }
        }).start();
    }

爲什麼呢?之前一直強調只能在主線程中執行。

換成Toast

  private void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //textView.setText("我在測試~~~~");
                Toast.makeText(MainActivity.this,"我在測試",Toast.LENGTH_SHORT).show();

            }
        }).start();
    }
E/AndroidRuntime: FATAL EXCEPTION: Thread-2
                                                                            Process: com.netease.handler.sample, PID: 28357
                                                                            java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
                                                                                at android.widget.Toast$TN.<init>(Toast.java:407)
                                                                                at android.widget.Toast.<init>(Toast.java:121)
                                                                                at android.widget.Toast.makeText(Toast.java:286)
                                                                                at android.widget.Toast.makeText(Toast.java:276)
                                                                                at com.netease.handler.sample.MainActivity$3.run(MainActivity.java:60)
                                                                                at java.lang.Thread.run(Thread.java:919)

再換一下:

    private void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(1000);
               textView.setText("我在測試~~~~");
               // Toast.makeText(MainActivity.this,"我在測試",Toast.LENGTH_SHORT).show();

            }
        }).start();
    }

閃退:

   android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

爲什麼呢??

我們進入TextView中:

找到這樣的方法

  if (mLayout != null) {
            checkForRelayout();
        }
    /**
     * Check whether entirely new text requires a new view layout
     * or merely a new text layout.
     */
    private void checkForRelayout() {
        // If we have a fixed width, we can just swap in a new text layout
        // if the text height stays the same or if the view height is fixed.

        if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT
                || (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth))
                && (mHint == null || mHintLayout != null)
                && (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
          
    //省略...


            requestLayout();
            invalidate();
        } else {
            // Dynamic width, so we have no choice but to request a new
            // view layout with a new text layout.
            nullLayouts();
            requestLayout();
            invalidate();
        }
    }

都執行了這兩個方法

  requestLayout();
  invalidate();

requestLayout是View中的方法

  /**
     * Call this when something has changed which has invalidated the
     * layout of this view. This will schedule a layout pass of the view
     * tree. This should not be called while the view hierarchy is currently in a layout
     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
     * end of the current layout pass (and then layout will run again) or after the current
     * frame is drawn and the next layout occurs.
     *
     * <p>Subclasses which override this method should call the superclass method to
     * handle possible request-during-layout errors correctly.</p>
     */
    @CallSuper
    public void requestLayout() {
        if (mMeasureCache != null) mMeasureCache.clear();

        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
            // Only trigger request-during-layout logic if this is the view requesting it,
            // not the views in its parent hierarchy
            ViewRootImpl viewRoot = getViewRootImpl();
            if (viewRoot != null && viewRoot.isInLayout()) {
                if (!viewRoot.requestLayoutDuringLayout(this)) {
                    return;
                }
            }
            mAttachInfo.mViewRequestingLayout = this;
        }

        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
        mPrivateFlags |= PFLAG_INVALIDATED;

        if (mParent != null && !mParent.isLayoutRequested()) {
            mParent.requestLayout();
        }
        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
            mAttachInfo.mViewRequestingLayout = null;
        }
    }

先看一下實現關係

ViewRootImpl:
public final class ViewRootImpl implements ViewParent,
mParent  
protected ViewParent mParent;ViewParent是個接口
      mParent.requestLayout();

追蹤:

ViewRootImpl #requestLayout()

    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
  void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

這個異常就是TextView.setTextView中出現的異常,但是如果  invalidate();  在    checkThread(); 方法執行前就執行完,那麼就不會報異常。所以,TextView.setTextView只能在主線程執行這句話是錯的  ,因爲太過於絕對。

5:new Handler兩種寫法有什麼區別?

上面有兩種實現方式

我們先看如何去取消息:

ActivityThread#main()方法

  public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

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

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//關注這句話
        Looper.loop();

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

  Looper.loop();

  public static void loop() {
        final Looper me = myLooper();
//省略

//關注這個循環
       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;
            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;
            try {
                 //通過handler去分發消息
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                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;
                    }
                }
            }
           
//省略
       

            msg.recycleUnchecked();
        }
    }
msg.target就是handler
    
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            //先關注這個方法  先判斷mCallBack,如果不等於null那麼就繼續執行
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

其實沒啥區別,當(mCallback.handleMessage(msg))爲false的時候,就會去執行下面的handlerMessage方法,下面的就是一個可以重寫的方法。所以把第二種方法叫備胎方法。

6:ThreadLocal用法和原理

正常的

Looper#中的ThreadLocal是Looper類型,且是static類型的
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

測試下面常用的源碼中的方法

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

 

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
    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();
    }

 

    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }
 protected T initialValue() {
        return null;
    }

 Demo

public class ThreadLocalTest {

    @Test
    public void test() {
        // 創建本地線程(主線程)---簡單測試
        final ThreadLocal<String> threadLocal = new ThreadLocal<String>() {
            @Override
            protected String initialValue() {
                // 重寫初始化方法,默認返回null,如果ThreadLocalMap拿不到值再調用初始化方法
                return "馮老師";
            }
        };

        // 從ThreadLocalMap中獲取String值,key是主線程
        System.out.println("主線程threadLocal:" + threadLocal.get());

        //--------------------------thread-0
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 從ThreadLocalMap中獲取key:thread-0的值?沒有,拿不到值再調用初始化方法
                String value1 = threadLocal.get();
                System.out.println("thread-0:" + threadLocal.get()); // 馮老師

                // ThreadLocalMap存入:key:thread-0  value:"熊老師"
                threadLocal.set("熊老師");
                String value2 = threadLocal.get(); // 可以get到了
                System.out.println("thread-0  set  >>> " + threadLocal.get()); // 熊老師

                // 使用完成建議remove(),避免大量無意義的內存佔用
                threadLocal.remove();
            }
        });
        thread.start();

        //--------------------------thread-1
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                // 從ThreadLocalMap中獲取key:thread-1的值?沒有,拿不到值再調用初始化方法
                String value1 = threadLocal.get();
                System.out.println("thread-1:" + threadLocal.get()); // 馮老師

                // ThreadLocalMap存入:key:thread-1  value:"彭老師"
                threadLocal.set("彭老師");
                String value2 = threadLocal.get(); // 可以get到了
                System.out.println("thread-1  set  >>> " + threadLocal.get()); // 彭老師

                // 使用完成建議remove(),避免大量無意義的內存佔用
                threadLocal.remove();
            }
        });
        thread2.start();
    }
}

 

原理就是:注意Threadlocal最後的存取是以鍵值對的形式存在的,鍵就是當前的線程。

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章