Handler
1、说明
1)在主线程中可以直接创建Handler对象,而在子线程中需要先调用Looper.prepare()才能创建Handler对象,创建Handler后,Looper.loop()。否则运行抛出”Can’t create handler inside thread that has not called Looper.prepare()”异常信息。
2)每个线程中最多只能有一个Looper对象,否则抛出异常。
3)一个Looper只能对应了一个MessageQueue。
4)可以通过Looper.myLooper()获取当前线程的Looper实例,通过Looper.getMainLooper()获取主(UI)线程的Looper实例。
5)一个线程中只有一个Looper实例,一个MessageQueue实例,可以有多个Handler实例。
6)Handler不是不是线程,是通知线程的辅助。
2、示例:Runnable就是可执行体,仍在主线程中,只是刷新主线程界面
Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (!run)
return;
// Log.e("test", "Runnable--" + Thread.currentThread().getName());
setProgress(seekPos);
if (seekPos < 100) {
seekPos++;
} else {
seekPos = 0;
}
seekHandler.sendEmptyMessageDelayed(0, 50);
}
};
private Handler seekHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
seekHandler.post(mRunnable);
}
};
3、示例:两个子线程每隔1s相互发送消息打印日志
MainActivity.java
public class MainActivity extends Activity {
ThreadA a;
ThreadB b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = new ThreadA();
b= new ThreadB();
a.toGetThread(b);//向ThreadA中传入B的引用
b.toGetThread(a);
a.start();//开始线程
b.start();
}
}
ThreadA.java
public class ThreadA extends Thread {
Handler aHandler;
private ThreadB threadb;
public ThreadB toGetThread(ThreadB threadB){
threadb = threadB;
return threadb;
}
@Override
public void run() {
super.run();
Looper.prepare();
aHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==1){
Log.d("Thread", "This is Thread one" + currentThread().getId());
sendb();
}
}
};
Looper.loop();
}
public void sendb() {
if(threadb.bHandler==null){
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
threadb.bHandler.sendEmptyMessageDelayed(2, 1000);//在ThreadA中向ThreadB中的Handler发送消息。
}
}
}
ThreadB.java
public class ThreadB extends Thread {
private ThreadA threada;
Handler bHandler;
public ThreadA toGetThread(ThreadA threada){
this.threada =threada;
return threada;
}
@Override
public void run() {
super.run();
Looper.prepare();
bHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==2){
Log.d("Thread", "This is Thread Two" + currentThread().getId());
senda();
}
}
};
senda();
Looper.loop();//Looper.loop()是一个死循环
}
public void senda() {
if(threada.aHandler==null){
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
threada.aHandler.sendEmptyMessageDelayed(1, 1000);//在ThreadB中向ThreadA中的Handler发送消息。
}
}
}