handler 定义:
Handler
是用来结合线程的消息队列来发送、处理Message对象
和Runnable对象
的工具。每一个Handler
实例之后会关联一个线程和该线程的消息队列。当你创建一个Handler的时候,从这时开始,它就会自动关联到所在的线程/消息队列
,然后它就会陆续把Message/Runnalbe
分发到消息队列,并在它们出队的时候处理掉。
handler用途:
1、推送未来某个时间点需要执行的Message或者Runnable操作到消息队列
MyHandler mHandler = new MyHandler(this);
class MyHandler extends Handler {
private WeakReference<TestActivity> weakReference;
public MyHandler(TestActivity activity) {
weakReference = new WeakReference<TestActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
final TestActivity testActivity = weakReference.get();
if (testActivity != null) {
textView.setText("" + msg.what);
}
}
}
//message方式
for (int i = 1; i <= 10; i++) {
Message message = Message.obtain(mHandler);
message.what = 10 - i;
mHandler.sendMessageDelayed(message, 1000 * i); //通过延迟发送消息,每隔一秒发送一条消息
}
-----------------------------------------
//runable方式,这种方式不用覆写handleMessage
for (int i = 1; i <= 10; i++) {
final int finalI = i;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
textView.setText((10 - finalI) + "");
}
}, 1000 * i);
}
//不管哪种方式,都要记得释放资源
@Override
protected void onDestroy() {
mHandler.removeCallbacksAndMessages(null);
mHandler = null;
super.onDestroy();
}
上述代码中我们采用了内部类,会强引用外部类,所以我们必须添加处理,这里采用弱引用方式。
2、在子线程把需要在另一个线程执行的操作加入到消息队列中去。
在子线程进行使用的时候,我们必须多了解几个概念:
Looper:
handler 创建的时候必须对应创建相应的looper
,如果我们在UI线程创建的话系统会帮我们创建。每一个线程只有一个Looper
,每个线程在初始化Looper之后,然后Looper会维护好该线程的消息队列
,用来存放Handler
发送的Message
,并处理消息队列出队的Message
。它的特点是它跟它的线程是绑定的,处理消息也是在Looper
所在的线程去处理,所以当我们在主线程创建Handler时,它就会跟主线程唯一的Looper
绑定,从而我们使用Handler
在子线程发消息时,最终也是在主线程处理,达到了异步的效果。
MessageQueue
MessageQueue是一个消息队列,用来存放Handler发送的消息, 每个线程最多只有一个MessageQueue, MessageQueue通常都是由Looper来管理。
Message
消息对象,就是MessageQueue里面存放的对象,一个MessageQueu可以包括多个Message。当我们需要发送一个Message时,我们一般不建议使用new Message()的形式来创建,更推荐使用Message.obtain()来获取Message实例,因为在Message类里面定义了一个消息池,当消息池里存在未使用的消息时,便返回,如果没有未使用的消息,则通过new的方式创建返回,所以使用Message.obtain()的方式来获取实例可以大大减少当有大量Message对象而产生的垃圾回收问题。
下面请看在子线程中如何使用:
//线程中使用,方式一
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Handler handler=new Handler(Looper.myLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("Looper.prepare()");
}
});
}
}, 2000 );
Looper.loop();
}
}).start();
//线程中使用,方式二
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
textView.setText("Looper.prepare()");
}
}, 2000);
Looper.loop();
}
}).start();
发现上诉使用的区别了吧,如果传入的是UI线程的looper,则结果处理函数里面其实是在主线程进行操作的。
HandlerThread
这个是个什么玩意儿,其实它就是handler+thread的升级版,请看源码:
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
/**
* @return a shared {@link Handler} associated with this thread
* @hide
*/
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}
/**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
/**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* {@link #getLooper} returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
/**
* Returns the identifier of this thread. See Process.myTid().
*/
public int getThreadId() {
return mTid;
}
}
里面有个run方法,和我们子线程使用handler极其相似。从源码可以看到,HandlerThread集成于Thread,然后覆写run方法,进行Looper的创建,从而通过getLooper方法暴露出该线程的Looper对象,同时,HandlerThread 也增加了同步锁,方便我们在多线程并发情况下执行。使用如下:
final HandlerThread handlerThreadA=new HandlerThread("handlerThread A");
handlerThreadA.start();
Handler handlerA=new Handler(handlerThreadA.getLooper());
handlerA.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("tag","HandlerThread AAAAAA");
}
},1000);
final HandlerThread handlerThreadB=new HandlerThread("handlerThread B");
handlerThreadB.start();
Handler handlerB=new Handler(handlerThreadB.getLooper());
handlerB.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("tag","HandlerThread BBBBB");
}
},2000);
一般情况下,handler开发所涉及的技巧就差不多说完了。
网友评论