前言
Android 提供了Handler和Looper来来满足线程间的通信,而前面我们所说的IPC指的是进程间的通信。这是两个完全不同的概念。
Handler先进先出原则,Looper类用来管理特定线程内消息的交换(MessageExchange);
1、为什么会有Handler机制?
我们刚说Handler机制的主要作用是将某一任务切换到特定的线程来执行,我们做项目可能都遇到过ANR(Application Not Response)
,这就是因为执行某项任务的时间太长而导致程序无法响应。这种情况我们就需要将这项耗时较长的任务移到子线程来执行,从而消除ANR。而我们都知道Android规定访问UI只能在主线程中进行,如果在子线程中访问UI,那么程序就会抛出异常。而Android提供Handler就是为了解决在子线程中无法访问UI的矛盾。
2、Handler源码解析
子线程中创建Handler为啥会报错?
首先,我们先看一个例子,我们在子线程中创建一个Handler。
new Thread(new Runnable() {
@Override
public void run() {
new Handler(){
@Override
public void handleMessage (Message message){
super.handleMessage(message);
}
};
}
},"MyThread").start();
我们运行时会发现,会抛出异常:Can't create handler inside thread that has not called Looper.prepare()
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:204)
at android.os.Handler.<init>(Handler.java:118)
at com.example.bthvi.myconstrainlayoutapplication.MainActivity$1$1.<init>(MainActivity.java:21)
at com.example.bthvi.myconstrainlayoutapplication.MainActivity$1.run(MainActivity.java:21)
at java.lang.Thread.run(Thread.java:764)
究竟是为什么会抛出异常呢?下面我们通过Handler源码来看看。
Handler的构造方法
当我们创建Handler对象的时候调用的是下面的方法:
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.