ActivityThread.java:
package com.metre.core;
public class ActivityThread {
public static void main(String[] args) throws Exception {
//初始化全局唯一主线程的Looper对象,和MessageQueue消息队列
Looper.prepare();
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println(msg.toString());
}
};
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.obj = "你好 小米!";
handler.sendMessage(message);
}
}).start();
//循环取出消息
Looper.loop();
}
}
Handler.java :
package com.metre.core;
public class Handler {
MessageQueue mQueue;
public Handler() throws Exception {
Looper looper = Looper.myLooper();
if(looper == null) {
throw new Exception("Can't create Handler inside thread "+Thread.currentThread()+" that has not called Looper.prepare()");
}
mQueue = looper.mQueue;
}
public void sendMessage(Message msg) {
enqueueMessage(msg);
}
private void enqueueMessage(Message msg) {
msg.target = this;
mQueue.enqueueMessage(msg);
}
public void handleMessage(Message msg) {
}
public void dispatchMessage(Message msg) {
handleMessage(msg);
}
}
Looper.java
package com.metre.core;
public class Looper {
static ThreadLocal<Looper> mThreadLocal = new ThreadLocal();
static MessageQueue mQueue;
public Looper() {
mQueue = new MessageQueue();
}
public static void prepare() throws Exception{
if(mThreadLocal.get() != null) {
throw new Exception("Only one Looper may be created per Thread.");
}
mThreadLocal.set(new Looper());
}
public static void loop() {
while(true) {
Message message = mQueue.next();
message.target.dispatchMessage(message);
}
}
public static Looper myLooper(){
return (Looper)mThreadLocal.get();
}
}
Message.java:
package com.metre.core;
public class Message {
public Object obj;
public Handler target;
public int what;
@Override
public String toString() {
return "Message [obj=" + obj.toString() + "]";
}
}
MessageQueue.java
package com.metre.core;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class MessageQueue {
BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue(50);
public void enqueueMessage(Message msg) {
try {
blockingQueue.put(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Message next() {
try {
return blockingQueue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}