一. Handler
public class Handler {
Looper mLooper;
public Handler() {
mLooper = Looper.myLooper();
}
public void sendMessage(Message msg) {
enqueueMessage(msg);
}
private void enqueueMessage(Message msg) {
msg.target = this;
mLooper.messageQueue.enqueueMessage(msg);
}
public void handleMessage(Message msg) {
}
}
二. Message
public class Message {
String obj;
Handler target;
public Message() {
}
public Message(String obj) {
this.obj = obj;
}
public String toString(){
return obj.toString();
}
}
三. MessageQueue
public class MessageQueue {
BlockingQueue<Message> queue = new ArrayBlockingQueue<>(100);
public void enqueueMessage(Message msg) {
try {
queue.put(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Message next() {
Message msg = null;
try {
msg = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return msg;
}
}
四. Looper
public class Looper {
static ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();
MessageQueue messageQueue;
private Looper() {
messageQueue = new MessageQueue();
}
public static Looper myLooper() {
return sThreadLocal.get();
}
public static void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
public static void looper() {
final Looper me = myLooper();
final MessageQueue queue = me.messageQueue;
for (; ; ) {
Message msg= queue.next();
msg.target.handleMessage(msg);
}
}
}
五. 测试
private static Handler handler111;
public static void main(String[] args) {
Looper.prepare();
handler111 = new Handler() {
@Override
public void handleMessage(Message msg) {
System.out.println("handler111 " + msg + " thread " + Thread.currentThread().getName());
}
};
new Thread() {
@Override
public void run() {
handler111.sendMessage(new Message("david---->jett"));
}
}.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.looper();
}
六. 代码地址
https://gitee.com/luisliuyi/android-handler.git
网友评论