一.什么是Handler
Handler通过发送和处理Message和Runnable对象来关联对应线程的MessageQueue。1.可以让对应的Message和Runnable在未来的某个时间点进行相应处理 2.让自己想要处理的耗时操作放在子线程中,让更新UI的操作放在主线程。
二.handler的使用方法
post(Runnalbe)
public class HandlerActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handlerctivity);
mTextView = findViewById(R.id.textContent);
}
public void startDownload(View view) {
DownLoadThread downLoadThread = new DownLoadThread();
downLoadThread.start();
System.out.println("当前的线程UI:" + Thread.currentThread().getId());
}
class DownLoadThread extends Thread {
@Override
public void run() {
super.run();
try {
System.out.println("当前的线程:" + Thread.currentThread().getId());
System.out.println("开始下载");
Thread.sleep(5000);
System.out.println("下载完成");
Runnable runnable = new Runnable() {
@Override
public void run() {
mTextView.setText("下载完成");
}
};
mHandler.post(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
sendMessage(message)
三.handler机制的原理
三个线程,对同一个变量赋值取值,原以为结果是3个值,事实上。。。
public class ThreadLocalActivity extends AppCompatActivity {
private String content;
private String value1;
private String value2;
private String value3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_local);
}
public void test(View view) {
try {
new Thread1().start();
new Thread2().start();
setContent("value33333");
Thread.sleep(5000);
value3 = getContent();
Log.e("tag", "value1111" + value1);
Log.e("tag", "value222" + value2);
Log.e("tag", "value333" + value3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class Thread1 extends Thread {
@Override
public void run() {
super.run();
try {
setContent("valueThread1111");
Thread.sleep(2000);
value1 = getContent();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Thread2 extends Thread {
@Override
public void run() {
super.run();
try {
setContent("value2222");
Thread.sleep(2000);
value2 = getContent();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
打印结果:
02-05 15:26:14.973 31739-31739/com.ww.interviewdemo E/tag: value1111value2222
02-05 15:26:14.973 31739-31739/com.ww.interviewdemo E/tag: value222value2222
02-05 15:26:14.973 31739-31739/com.ww.interviewdemo E/tag: value333value2222
ThreadLocal实现不同线程的数据副本
public class ThreadLocalActivity extends AppCompatActivity {
private String content;
private String value1;
private String value2;
private String value3;
private ThreadLocal threadLocal = new ThreadLocal<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_local);
}
public void test(View view) {
try {
new Thread1().start();
new Thread2().start();
threadLocal.set("333333");
Thread.sleep(5000);
value3 = threadLocal.get();
Log.e("tag", "value1111" + value1);
Log.e("tag", "value222" + value2);
Log.e("tag", "value333" + value3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class Thread1 extends Thread {
@Override
public void run() {
super.run();
try {
threadLocal.set("valueThread1111");
Thread.sleep(2000);
value1 = threadLocal.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Thread2 extends Thread {
@Override
public void run() {
super.run();
try {
threadLocal.set("value2222");
Thread.sleep(2000);
value2 = threadLocal.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
02-05 15:48:18.812 3181-3181/com.ww.interviewdemo E/tag: value1111valueThread1111
02-05 15:48:18.812 3181-3181/com.ww.interviewdemo E/tag: value222value2222
02-05 15:48:18.812 3181-3181/com.ww.interviewdemo E/tag: value333333333
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);
}
get方法
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();
}
- Looper
先提出一个问题,子线程中可以创建Handler吗?
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();(第二次添加的)
Handler handler=new Handler();
}
}).start();
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
少一个Looper.prepare()方法,那就添加一个
从 Looper.prepare();开始看起
static final ThreadLocal sThreadLocal = new ThreadLocal(); 里面存储的是Looper
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));
}
sThreadLocal.get() 获得对应线程的Looper,多次调用prepare后,sThreadLocal.get()!=null,会产生异常,说明一个线程一个有一个Looper。 sThreadLocal.set(new Looper(quitAllowed))这一步有两个作用,一个是生成一个Looper实例,二是把Looper添加到ThreadLocal里面。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
从这里可以看出 Looper、MessageQueue、Thread是1:1:1的关系
/** 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的介绍(大体意思):初始化带有Looper的线程 , 用一个Looper初始化当前的一个线程 ,还有两个方法 #loop()、#quit(),Looper的作用是不断轮询,查看队列中是否有消息,如果有消息,立即处理消息,如果没有消息,进入阻塞状态。
消息的发送和处理过程
1.消息入列
post()
postAtTime(Runnable r, long uptimeMillis)
postDelayed(Runnable r, long delayMillis)
postAtFrontOfQueue(Runnable r)
但这些方法最后都会调用这一个方法:
sendMessageAtTime(Message msg, long uptimeMillis)
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);
}
mQueue就是Looper中的MessageQueue
enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
msg.target = this中的this指的是当前Handler对象,有两个意思,第一:消息由当前Handler产生;第二:消息由当前Handler处理,然后把消息放入队列中,说到队列,队列里的消息谁在前谁在后,谁先执行谁后执行,与uptimeMillis有关。这个uptimeMillis是绝对时间,如果值很小就先执行。
再来看一下这个方法:postAtFrontOfQueue(字面意思:发送消息放到队列的最前面)
public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);//入队的时间是0,放 到了最前面
}
消息的出队
消息入队后,Looper的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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
//msg.target指的是Handler ,消息出队!!!
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
处理消息
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
msg.callback其实指的是Runnable(我们平时用post(new Runnalbe)的写法)
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
再回到dispatchMessage中,如果msg.callback != null,调用handleCallback(msg)
private static void handleCallback(Message message) {
message.callback.run();
}
其实就是调用Runnable重写的run方法
继续看dispatchMessage(),mCallback从哪里来的?
先看看构造函数
public Handler(Callback callback) {
this(callback, 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());
}
}
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时,一般不传入callback,如果callback不为空,调用mCallback.handleMessage(msg),如果返回true,直接return,返回false,调用 handleMessage(msg);方法
public interface Callback {
public boolean handleMessage(Message msg);
}
private Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;//重写 true或者false
}
}){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
} ;
空方法,需要子类自己去实现
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
总结一下:msg.callback是我们传入的Runnable,mCallback是通过构造函数传入的
四.handler引发的内存泄漏以及解决办法
1.ANR
class Thread1 extends Thread {
@Override
public void run() {
super.run();
mHandler.post(new Runnable() {
@Override
public void run() {
//在这里面进行一些耗时操作,错错错!!!
String text = "更新UI";
mTextView.setText(text);
}
});
}
}
有人以为是子线程,所有进行了一些耗时操作,其实还是在主线程中。我们这里的post(Runnalbe)其实和sendMessage是一样的,只不过Runnable被封装成Message,还是在主线程中处理消息。
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
也是在主线程中运行,不能进行耗时操作。
2.内存泄漏
我们平时创建的Handler的方法
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
警告:This Handler class should be static or leaks might occur (anonymous android.os.Handler) less..,应该匿名内部类持有Activity的引用,造成内存泄漏
静态内部类
强引用(StrongReference):强引用是使用最普遍的引用。如果一个对象具有强引用,那垃圾回收器绝不会回收它
软引用(SoftReference): 如果一个对象只具有软引用,则内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。
弱引用(WeakReference)
在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。
private static class MyHandler extends Handler{
private WeakReference activityWeakReference;
public MyHandler(WeakReference activityWeakReference) {
this.activityWeakReference = activityWeakReference;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(activityWeakReference.get()!=null){
//TODO
}
}
}