Handler常见疑问

首先是来一段写了一万遍的代码,Handler的基本使用

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            textView.setText("二二三四");
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
        textView.setText("一二三四");

        handlerTest();
    }

    private void handlerTest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = handler.obtainMessage();
                handler.sendMessage(message);
            }
        }).start();
    }
}

毫无疑问textView直接被改成了“二二三四”,那第一个问题问题来了:

一、可不可以在子线程里直接修改textView内容,这样的代码:

public class MainActivity extends AppCompatActivity {

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        handlerTest();
    }

    private void handlerTest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                textView.setText("二二三四");
            }
        }).start();
    }
}

先不要着急否定,运行一下试试:


子线程中修改textView为“二二三四”

再加一句代码:

public class MainActivity extends AppCompatActivity {

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        handlerTest();
    }

    private void handlerTest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //添加一秒延迟
                SystemClock.sleep(1000);
                textView.setText("二二三四");
            }
        }).start();
    }
}

setText()之前加了一秒延迟,在运行一下,没图,直接炸了,错误信息:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
  at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7286)
  at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1155)

Only the original thread that created a view hierarchy can touch its views.这一句说的很明显,但是为什么不加延迟就可以,直接去看下源码找原因,setText()方法点进去一步步跟踪:

    private void setText(CharSequence text, BufferType type,
                         boolean notifyBefore, int oldlen) {
        ...
        if (mLayout != null) {
            checkForRelayout();
        }

        ...
    }

这里的checkForRelayout()再点进去:

    private void checkForRelayout() {
        ...

        if (...)
            ...
            requestLayout();
            invalidate();
        } else {
            ...
            requestLayout();
            invalidate();
        }
    }

发现这里无论如何都会走requestLayout();invalidate();requestLayout()再继续跟:

    public void requestLayout() {
       ...

        if (...) {
            ...
            ViewRootImpl viewRoot = getViewRootImpl();
            ...
        }

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

这里就发现了跟错误信息有些对上了,错误信息的定位是这样的:

at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7286)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1155)

但是我们跟踪到的是mParent.requestLayout();虽然上面有个ViewRootImpl,这个mParentViewParent类型,点ViewParent会发现这是个接口,而ViewRootImpl正实现了这个接口,所以我们直接可以去ViewRootImpl里找错误信息里的requestLayout()方法,这里显特别注意一点,一会要用,就是如果mParent != null,才会继续进行下面的requestLayout()

    @Override
    public void requestLayout() {
        if (...) {
            checkThread();
            ...
        }
    }

这里也发现了错误信息里的下一层方法checkThread(),再跟进去:

    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

这里就是导致崩溃的CalledFromWrongThreadException,只要mThread != Thread.currentThread()成立就会报错,这里报错其实是可以理解的,因为我们是在子线程里调用setText(),所以Thread.currentThread()获取到的一定是子线程,并不是主线程mThread,mThread是ViewRootImpl初始化是存储的赋值的,所以直接抛出异常。那为什么不延迟的情况下不报错呢?上面提到过特别注意的那一点就是如果mParent != null,才会继续进行下面的requestLayout(),那这个mParent也就是ViewRootImpl是在ActivityThreadhandleResumeActivity(..)中创建的,是在主线程中,所以如果setText的子线程如果在ViewRootImpl创建之前执行了,那么requestLayout();并不会报出异常,会继续执行invalidate();,控件也就被刷行了。

二、Handler内存泄漏测试

还是一段常见的代码:

public class MainActivity extends AppCompatActivity {

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAnotherActivity();
            }
        });
    }
    
    private void startAnotherActivity(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(3000);
                Message message = handler.obtainMessage();
                message.what = 666;
                handler.sendMessage(message);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: ");
    }
}

点击发送消息,收到消息跳转。一般在线程都会进行一个耗时操作,这里用个3秒延迟模拟下,点击跳转然后再3秒延迟之内关闭Activity,结果就是3秒过后还是跳转了,而且第一个Activity的onDestroy()也执行了。这里就是发生了内存泄漏,运行效果:


Activity还是打开了

这种泄漏怎么处理,先看这种方式:

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: ");
        handler.removeMessages(666);
    }

这种方式是不行的,解决不了问题,因为在onDestroy()执行的时候,延迟还没有结束,所以message并没有在消息队列中,这样移除的话,必须要发送的时候同时改变才可以:

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = handler.obtainMessage();
                message.what = 666;
                handler.sendMessageDelayed(message, 3000);
            }
        }).start();

这样会直接把message放入消息队列,三秒后执行,所以这样再removeMessages()是会起作用的。但是这样很难用,一般我的做的耗时操作,比如网络请求,并不能知道时长,我们需要的就是再耗时执行完成后发动消息,也就是说如果一定要用SystemClock.sleep(3000),怎么解决内存泄漏?很简单:

public class MainActivity extends AppCompatActivity {

   ...
    private void startAnotherActivity(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(3000);
                if (handler != null){
                    Message message = handler.obtainMessage();
                    message.what = 666;
                    handler.sendMessage(message);
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: ");
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}

三、Handler的另一种写法

可能有时候看到有的Handler不是这样写的,两种写法比较一下:

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

    private Handler handler2 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

这两种都可以实现消息接受,去源码里看看有什么区别,关于Loop、MessageQueue、Message这里不再展开,直接这里从ActivityThread里看Handler是如何接收消息的,在ActivityThread的main函数里:

    public static void main(String[] args) {
        ...
        Looper.loop();
        ...
    }

然后点这个loop()继续跟:

    public static void loop() {
        ...
        for (;;) {
            Message msg = queue.next();
            ...

            msg.target.dispatchMessage(msg);
            ...
        }
    }

这里是一个无限的循环,不停的去消息队列里取下一条,然后调用了msg.target.dispatchMessage(msg),这个target是什么?他其实就是handler,可以去Message源码里看一下是这样的:

public final class Message implements Parcelable {
    ...
    Handler target;
    ...
}

那直接可以去Handler源码中找dispatchMessage()方法:

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

而这里的mCallback就是第一种Handler创建时候传递过来的Callback,那么这里一目了然,最外层的if中msg.callback我们这里不用关心,直接进去else中,如果mCallback有值,优先执行mCallback.handleMessage(msg),执行完之后直接return,不会再执行Handler的handleMessage(msg),所以两种Handler的写法都能实现消息传递,但是第二种写法也就是没有Callback的那种,是有黄色警告的,所以推荐使用第一种Callback的写法。
这里还有个问题,就是mCallback.handleMessage(msg)的返回值,看上面这段代码的意思,如果返回true直接return了还好,如果返回false还是会执行Handler的handleMessage(msg);,也就是说既传递了Callback又重写了Handler的handleMessage(msg)会有什么效果?比如这样的代码:

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Log.e(TAG, "Callback的handleMessage");
            return false;
        }
    }){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e(TAG, "Handler的handleMessage");
        }
    };

这样写的话,第一个handleMessage()的返回值直接影响第二个handleMessage()是否被调用,如果不重写第二个handleMessage(),也就是Handler中的handleMessage()的方法,那第一个里的返回值就没什么意义了,因为Handler源码中的handleMessage()是一个空的方法。

四、为什么不能在子线程中new Handler() ?

public class MainActivity extends AppCompatActivity {

    ...
    private void startAnotherActivity(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                new Handler();
            }
        }).start();
    }
    ...
}

运行一下直接炸:

    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:203)
        at android.os.Handler.<init>(Handler.java:117)
        at com.yu.handlertest.MainActivity$4.run(MainActivity.java:58)
        at java.lang.Thread.run(Thread.java:764)

这个点进去Handler源码就能看到原因:

    public Handler(Callback callback, boolean async) {
        ...

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        ...
    }

    ...

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

这个myLooper ()方法的注释写的也很清楚,获取当前线程的Looper对象很显然这个线程里我没没有Looper对象,那问题来了,主线程里我们也没创建,为什么没问题?
这个还是看ActivityThread类的源码可以找到原因,ActivityThread是在程序一打开就会被创建的,ActivityThread的main函数有调用这一个方法:

    public static void main(String[] args) {
        ...

        Looper.prepareMainLooper();
        ...
    }

到Looper类中跟一下这个方法:

    public static void prepareMainLooper() {
        prepare(false);
        ...
    }

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

这里就证明ActivityThread的mian函数里会进行sThreadLocal.set()操作,所以在在主线程中创建Handler的时候,获取主线程的Loop对象时sThreadLocal.get()是有值的。这了可能有个疑问,同样是调用sThreadLocal.get(),并没有传递参数过去,是怎么区分线程的?继续看下一个问题:

五、ThreadLocal是什么?

打开ThreadLocal看他的get()方法:

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    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();
    }

这里就会发现,调用get的时候,他会以当前线程作为key去取值,取不到就会调用setInitialValue ()方法,直接撸一段代码看效果,上面Handler里的ThreadLocal中存的是Looper对象,这里用String做演示:

    ThreadLocal<String> threadLocal = new ThreadLocal<String>(){
        @Nullable
        @Override
        protected String initialValue() {
            return "默认值";
        }
    };

    private void testThreadLocal() {
        // 获取主线程中的值,这里应该输出默认值
        Log.e(TAG, "主线程修改前: " + threadLocal.get());
        // 在主线程修改threadLocal的值为:"A"
        threadLocal.set("A");
        // 获取主线程中的值,因为修改过,所以这里应该输出:"A
        Log.e(TAG, "主线程修改后: " + threadLocal.get());

        //Thread1
        new Thread(new Runnable() {
            @Override
            public void run() {
                //子线程中获取threadLocal的值,主线程中已经进行修改,看子线程中是什么值
                Log.e(TAG, "Thread1修改前: " + threadLocal.get());
                threadLocal.set("B");
                //子线程中获取threadLocal的值,子线程中已经进行修改,看子线程中是什么值
                Log.e(TAG, "Thread1修改后: " + threadLocal.get());
            }
        }).start();

        //Thread2
        new Thread(new Runnable() {
            @Override
            public void run() {
                //子线程中获取threadLocal的值,主线程中和另一个子线程中都已经进行修改,看子线程中是什么值
                Log.e(TAG, "Thread2修改前: " + threadLocal.get());
            }
        }).start();
    }

运行这个方法输出为:

E/MainActivity: 主线程修改前: 默认值
E/MainActivity: 主线程修改后: A
E/MainActivity: Thread1修改前: 默认值
E/MainActivity: Thread1修改后: B
E/MainActivity: Thread2修改前: 默认值

这样就很明白了,同一个ThreadLocal对象在不同线程中的set()和get()是互不相关的,set()方法只会影响当前线程的get()值,当然不重写initialValue()的话默认值是null