Android 子线程和子线程通过Handler通信
1、创建发送消息的子线程
创建一个Thread1类
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
//发送消息的子线程
public class Thread1 extends Thread {
private Handler handler;
public Thread1(Handler handler){
super.setName("Thread1");
this.handler=handler;
}
@Override
public void run() {
Message msg = Message.obtain();
msg.what = 1;
msg.obj = System.currentTimeMillis()+"";
handler.sendMessage(msg);
System.out.println((Thread.currentThread().getName() + "----发送了消息!" + msg.obj));
SystemClock.sleep(1000);
}
}
2、创建接收消息的子线程
创建一个Thread2类
import android.os.Handler;
import android.os.Looper;
//接收消息的子线程
public class Thread2 extends Thread{
private Handler handler2;
public Handler getHandler(){//注意哦,在run执行之前,返回的是null
return handler2;
}
public Thread2(){
super.setName("Thread2");
}
@Override
public void run() {
//在子线程里面新建Handler的实例,需要先调用Looper.prepare();否则会报错:Can't create handler inside thread that has not called Looper.prepare()
Looper.prepare();
handler2 = new Handler(){
public void handleMessage(android.os.Message msg) {
//这里处理消息
System.out.println(("收到消息了:" + Thread.currentThread().getName() + "----" + msg.obj));
};
};
Looper.loop();
}
}
3、编辑主函数
编辑MainActivity.class
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity{
private Handler myHandler=null;
private Thread2 thread1;
private Thread1 thread2;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.handler3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//在当前onclick方法中监听点击button的动作
thread1 = new Thread2();
thread1.start();
myHandler = thread1.getHandler();
while (myHandler == null) {
SystemClock.sleep(100);
myHandler = thread1.getHandler();
}
thread2 = new Thread1(myHandler);
thread2.start();
}
});
}
}
4、编写布局文件
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.kh17_1.MainActivity">
<Button
android:id="@+id/handler3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动子线程之间的通信" />
</RelativeLayout>
5、运行并观察结果
得到该输出:
两子线程成功实现通信~