如何使用Handler,为什么要使用Handler,什么时候使用Handler?
在Android中系统规定主线程(UI线程)不能阻塞超过5s,否则会出现"Application Not Responding"。也就是说,你不能在主线程中进行耗时操作(网络请求,数据库操作等),只能在子线程中进行。例如通过网络请求从服务端返回的数据需要更新UI,这时候就用到了Handler(因为handler可进行线程间的通讯)。
Handler有四大元素:
Handler、Mesage、Message Queue、Looper
Handler
定义:Handler是Message的主要处理者
作用:
1.负责将Message添加到消息队列中
2.处理Looper分派过来的Message
Mesage
定义:Handler接收和处理的消息对象,可以理解为封装了某些数据的对象
使用:后台线程处理完数据后需要更新UI,可发送一条包含更新信息的Message给UI线程(或有handler的线程)
Message Queue
定义:消息队列
作用:用来存放通过Handler发送的消息,按照先进先出的顺序排列
Looper
定义:循环器,不断的取出MessageQueue中的消息并传递给Handler
作用:循环取出MessageQueue的Message,将取出的Message交付给相应的Handler
注意:每个线程只能拥有一个Looper,但一个Looper可以和多个线程的Handler绑定,也就是说多个线程可以往一个Looper所持有的MessageQueue中发送消息,这给我们提供了线程之间通信的可能。
上面这个定义片段摘自网络
ps:我们在项目中会使用到大量的handler,这时候如果退出Activity的时候一定要记得销毁handler,并清空消息和CallBack,
handler.removeCallbacksAndMessages(null);
下面这是官方的解释:意思是说如果参数为null的话,会将所有的Callbacks和Messages全部清除掉。
这样就可以在activity推出的时候调用,有效避免内存泄漏。
Added in API level 1 Remove any pending posts of callbacks and sent
messages whose obj is token. If token is null, all callbacks and
messages will be removed.
接下来从源码扒一下Handler的流程:
1.在主线程或者一个子线程中创建Handler对象;
创建Handler的时候它有7个构造方法:
/*
* Set this flag to true to detect anonymous, local or member classes
* that extend this Handler class and that are not static. These kind
* of classes can potentially create leaks.
*/
private static final boolean FIND_POTENTIAL_LEAKS = false;
private static final String TAG = "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.
*/
public Handler() {
this(null, false);
}
/**
* Constructor associates this handler with the {@link Looper} for the
* current thread and takes a callback interface in which you can handle
* messages.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*
* @param callback The callback interface in which to handle messages, or null.
*/
public Handler(Callback callback) {
this(callback, false);
}
/**
* Use the provided {@link Looper} instead of the default one.
*
* @param looper The looper, must not be null.
*/
public Handler(Looper looper) {
this(looper, null, false);
}
/**
* Use the provided {@link Looper} instead of the default one and take a callback
* interface in which to handle messages.
*
* @param looper The looper, must not be null.
* @param callback The callback interface in which to handle messages, or null.
*/
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
/**
* Use the {@link Looper} for the current thread
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
public Handler(boolean async) {
this(null, async);
}
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
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(); // 得到当前线程的Looper对象,或通过Loop.getMainLooper()获得当前进程的主线程的Looper对象
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;
}
/**
* Use the provided {@link Looper} instead of the default one and take a callback
* interface in which to handle messages. Also set whether the handler
* should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param looper The looper, must not be null.
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
上面刚开始就告诉我们创建Handler如果不是静态的,会造成内存泄漏的;我们依次看一下这几个构造方法。
1.如果空参,不指定Looper对象,这个Handler会绑定到创建这个线程的线程上,消息处理回调也就在在创建线程中执行
PS:主线程中的Loop是在UI线程入口创建的,activity在UI线程中,但是activity并不是UI线程的入口,UI线程入口ActivityThread中,代码如下:
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(); // 创建Looper并ThreadLocal.set(looper);绑定
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler(); // 创建Handler
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop(); // Looper遍历消息队列
throw new RuntimeException("Main thread loop unexpectedly exited");
}
2.多了个CallBack回调接口,这其实是用来拦截处理消息的。请看下面的代码:
private static Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Toast.makeText(getApplicationContext(),"第一滴血",Toast.LENGTH_SHORT).show();
return false;
}
}){
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(),"敢死队",Toast.LENGTH_SHORT).show();
}
};
ps:在第5行我return true,结果吐司只显示“第一滴血”。
当return false时,结果吐司先显示“第一滴血”,紧接着显示“敢死队”;这样我们就可以知道,Callback其实是用来拦截处理消息的。
3.使用传进去的looper,通过指定Looper对象从而绑定相应线程,即给Handler指定Looper对象相当于绑定到了Looper对象所在的线程中。Handler的消息处理回调会在Looper对象所在线程中执行。
4.同时指定Looper和实现拦截消息的回调。
5.默认情况下都是同步的,调用这个方法可以设置“是否异步”
6和7和上面是一样的,就多了一个判断是否异步的入口。
2.Looper对象的创建和实例化;
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
上面注释讲的很清楚了初始化当前线程的looper
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
/**一个线程只能持有一个Looper实例,sThreadLocal保存线程持有的looper对象*/
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
/**sThreadLocal是一个ThreadLocal变量,用于在一个线程中存储变量,这里Looper变量就存放在ThreadLocal里*/
sThreadLocal.set(new Looper(quitAllowed));
}
下面我们看看Looper的构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); // 创建Looper时,会自动创建一个与之匹配的MessageQueue
mThread = Thread.currentThread(); // Looper对应的当前线程
}
获取当前线程中的looper;
/**
* 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();
}
获取当前线程中Looper所持有的MessageQueue:
/**
* Return the {@link MessageQueue} object associated with the current
* thread. This must be called from a thread running a Looper, or a
* NullPointerException will be thrown.
*/
public static @NonNull MessageQueue myQueue() {
return myLooper().mQueue;
}
再来看看looper是怎么从MessageQueue 取出消息,转达到handler的:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//myLooper()方法是返回sThreadLocal存储的Looper实例
final Looper me = myLooper();
//me==null就会抛出异常,说明looper对象没有被创建,
//也就是说loop方法必须在prepare方法之后运行,消息循环必须要先在线程中创建Looper实例
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//获取Looper实例中的消息队列mQueue,一个Looper持有一个MessageQueue
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 (;;) {
//next()方法用于取出消息队列中的消息,如果取出的消息为空,则线程阻塞,消息队列是一个链表结构
Message msg = queue.next(); // might block
//没有message即返回
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.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);
}
//将处理完的Message对象回收,以备下次obtain重复使用。
msg.recycleUnchecked();
}
}
ps:可以看出Looper的作用是:
1.实例化Looper对象本身(prepare()方法),创建与之对应的MessageQueue(looper()构造方法)
2.loop()方法不断从MessageQueue中取消息,派发给Handler,然后调用相应Handler的dispatchMessage()方法进行消息处理。
3.在handle中绑定Looper并从MessageQueue中获取消息;
在handle其中的一个构造函数中进行获取looper的:
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());
}
}
//Looper.myLooper()获得了当前线程保存的Looper实例
mLooper = Looper.myLooper();
//如果没有looper实例就会抛出异常,这说明一个没有创建looper的线程中是无法创建一个Handler对象的;
//子线程中创建一个Handler时需要创建Looper,且开启循环才能使用这个Handler
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//获取looper实例的MessageQueue,保证handler实例与looper实例的MessageQueue关联
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
Handler把消息传递到消息队列中:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//handler发出的消息最终会保存到消息队列中
return queue.enqueueMessage(msg, uptimeMillis);
}
在主线程中Handler是如何创建Looper的;
public static void main(String[] args) {
...
// 通过prepareMainLooper方法为主线程创建一个looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
// 开启消息循环
Looper.loop();
...
}
/**
* 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()方法用于创建一个looper对象
//主线程的消息循环是不允许退出的
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
这样就简单完成了线程间的通讯。
案例:
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
/**
* 进入今天的话题,弄清楚handler的来龙去脉
*/
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e(TAG,msg.obj.toString());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oneMethod();
}
private void oneMethod() {
new Thread(){
@Override
public void run() {
super.run();
// Message msg = new Message();
// Message msg = Message.obtain();// 这里我们的Message 已经不是 自己创建的了,而是从MessagePool 拿的,省去了创建对象申请内存的开销
Message msg = handler.obtainMessage(); // 这里我们的Message 已经不是 自己创建的了,而是从MessagePool 拿的,省去了创建对象申请内存的开销
// 所以开发中我们一般建议使用第二种或者第三种方式创建handler,性能好一点
msg.obj = "111";
handler.sendMessage(msg);
}
}.start();
}
}
打印结果:
还有一种使用what的:
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.fly.customview.customclock.invoke.HandlerTag;
/**
* 进入今天的课题,弄清楚handler的来龙去脉
*/
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case HandlerTag.ONE:
Log.e(TAG,msg.obj.toString() + "********ONE*******");
break;
case HandlerTag.TWO:
Log.e(TAG,msg.obj.toString() + "********TWO*******");
break;
case HandlerTag.THREE:
Log.e(TAG,msg.obj.toString() + "********THREE*******");
break;
case HandlerTag.FOUR:
Log.e(TAG,msg.obj.toString() + "********FOUR*******");
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoMethod();
}
private void twoMethod() {
new Thread(){
@Override
public void run() {
super.run();
Message msg = handler.obtainMessage(); // 这里我们的Message 已经不是 自己创建的了,而是从MessagePool 拿的,省去了创建对象申请内存的开销
msg.obj = "第一滴血";
msg.what = HandlerTag.ONE;
handler.sendMessage(msg);
}
}.start();
}
}
/**
* author:fly
* date:2017.3.14
* des: Handler的what的标记,因为接口的属性默认是public static final 常量,且必须赋初值
* modify:
*
*/
public interface HandlerTag {
int ONE = 1;
int TWO = 2;
int THREE = 3;
int FOUR = 4;
}
打印结果:
Handler中有三种获取Message的方法,如下:
//方法1
Message msg = new Message();
msg.what = 1;
msg.arg1 = 2;
msg.arg2 = 3;
msg.obj = "demo";
mHandler.sendMessage(msg);
//方法2
Message msg2 = mHandler.obtainMessage();
//obtainMessage();
//obtainMessage(what);
//obtainMessage(int what,Object obj);
//obtainMessage(int what,int arg1,int arg2);
//obtainMessage(int what,int arg1,int arg2,Object obj );
msg2.what = 1;
msg2.arg1 = 2;
msg2.arg2 = 3;
msg2.obj = "demo";
msg2.sendToTarget();
//方法3
Message msg3 = Message.obtain();
msg3.sendToTarget();
实际运用中,通常使用第二种方法或者第三种方法(其实是一样的,handler.obtainMessage最终也是调用了Message的obtain方法)。
在Message的官方文档中,有这样一句话:
While the constructor of Message is public, the best way to get one of these is to call Message.obtain() or one of the Handler.obtainMessage()
methods, which will pull them from a pool of recycled objects.
意思是说,虽然Message的构造方法是公共的(可以通过New操作创建一个Message对象),但获取实例最好的方式还是Message.obtain()或者 Handler.obtainMessage() ,这两种方法提供的对象是消息池中那些已经创建但不再使用的对象。节约了内存资源。
总结:
这基本是一个类似生产者消费者的模型,简单说如果在主线程的MessageQueue没有消息时,就会阻塞在loop的queue.next()方法里,这时候主线程会释放CPU资源进入休眠状态,直到有下个消息进来时候就会唤醒主线程,在2.2 版本以前,这套机制是用我们熟悉的线程的wait和notify 来实现的,之后的版本涉及到Linux pipe/epoll机制,通过往pipe管道写端写入数据来唤醒主线程工作。原理类似于I/O,读写是堵塞的,不占用CPU资源。
欢迎阅读。