Handler使用
private static Handler mHandler;
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
new Thread( new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
message.what = 0;
message.obj = "执行操作";
mHandler.sendMessage(message);
}
}).start();
// 为避免内存泄漏,可以在onDestroy()中调用该方法
handler.removeCallbacksAndMessages(null);
Handler实现原理
在创建Handler时,需要绑定一个Looper对象。但是我们平常没有设置过是因为UIThread已经调用了prepareMainLooper();
在初始化构造函数里,会先检查是否为static的类,否则会发出泄漏的警告。然后再创建一个Looper对象,mLooper = Looper.myLooper();
Looper类
使用ThreadLocal类来维护一个线程私有的Looper类。
在构造函数中,创建了一个MessageQueue消息队列。
在Looper.class中,维护了一个sMainLooper
是主线程的Looper对象。
调用loop()
方法,执行一个死循环,一直排查MessageQueue中是否有消息,如果有,发送给Handler。
在子线程中操作主线程,可以通过 Looper.prepare()//要执行的代码// Looper.loop() 实现
在ActivityThread-main方法中,已经调用了Looper.prepareMainLooper()
,
private static Looper sMainLooper; // guarded by Looper.class
/**
* 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();
}
}
/**
* Returns the application's main looper, which lives in the main thread of the application.
*/
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
WeakHandler
在Android中,我们会经常使用到Handler,由于Handler会持有Activity等对象,导致Activity无法正常释放。解决这个问题比较好的一种方式就是使用WeakHandler。WeakHandler的实现如下代码所示
public class WeakHandler extends Handler {
public static interface IHandler {
public void handlerMessage(Message msg);
}
private final WeakReference<IHandler> mWeakHandler;
public WeakHandler(IHandler handler) {
this.mWeakHandler = new WeakReference<IHandler>(handler);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
IHandler handler = mWeakHandler.get();
if (null == handler)
return;
handler.handlerMessage(msg);
}
}
WeakHandler用法
public class TestActivity extends BaseActivity implements WeakHandler.IHandler {
private final WeakHandler mHandler = new WeakHandler(this);
public void onCreate(Bundle savedInstanceBundle) {
super.onCreate(savedInstanceBundle);
TestThread thread = new TestThread(mHandler);
thread.start();
}
public void handleMessage(Message msg) {
// do something
}
}
public class TestThread extends Thread {
private final WeakHandler mHandler;
public TestThread(WeakHandler handler) {
mHander = handler;
}
publicvoid run() {
mHandler.sendMessage(0);
}
}
WeakHandler的其他作用
- 可以使用来做UI线程的延迟,代替View.post方法
- WeakHandler可以当计时器或者用在需要循环刷新的地方