package com.test.looper;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
public class MainActivity extends Activity {
private LooperThread looperThread;//自己实现的带有Looper的类
private HandlerThread handerThread;//使用sdk方便类,带有Looper
private Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
looperThread = new LooperThread();
looperThread.start();
looperThread.getHandler().sendEmptyMessage(1);
looperThread.exit();
handerThread = new HandlerThread("abc");
handerThread.start();
//Handler在构造时会关联一个Looper,如果空就会使用Looper.myLooper();详见源码
handler = new Handler(handerThread.getLooper()){
@Override
public void handleMessage(Message msg) {
Log.d("CYQ", "--->" + msg);
}
};
handler.sendEmptyMessage(100);
}
class LooperThread extends Thread {
private Handler mHandler;
private final Object mSync = new Object();
public void run() {
Looper.prepare();
synchronized (mSync) {
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
Log.d("CYQ", "--->" + msg);
}
};
mSync.notifyAll();
}
Looper.loop();
}
public Handler getHandler() {
synchronized (mSync) {
if (mHandler == null) {
try {
mSync.wait();
} catch (InterruptedException e) {
}
}
return mHandler;
}
}
public void exit() {
getHandler().post(new Runnable(){
public void run() {
Looper.myLooper().quit();
}});
}
}
}
发现sdk中有方便类,可以有另外一种实现方法
HandlerThread的Looper对象可以用于创建一个Handler