public class HandlerTestActivity extends AppCompatActivity {
Handler mainHandler;
TextView mTextView;
TextView mTextView1;Handler handlerThread1;
Handler handlerThread2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_test);
mTextView=findViewById(R.id.main_text);
mTextView1=findViewById(R.id.main_text1);
//子线程向主线程发消息
mainHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
mTextView.setText("mainHandler");
Log.e("当前子线程是1----->", Thread.currentThread()+"");
}
};
new Thread(){
@Override
public void run() {
mainHandler.sendEmptyMessage(1);
}
}.start();
//主线程向子线程发送消息
HandlerThread handlerThread=new HandlerThread("handlerThread123");
handlerThread.start();
handlerThread1=new Handler(handlerThread.getLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e("当前子线程是2----->", Thread.currentThread()+"");
try {
//延时操作
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//mTextView.setText("handler");
mainHandler.post(new Runnable() {
@Override
public void run() {
Log.e("当前子线程是3----->", Thread.currentThread()+"");
mTextView1.setText("handler1");
}
});
}
};
handlerThread1.sendEmptyMessage(1);
//子线程之前通信
new Thread(){
@Override
public void run() {
try {
//延时操作
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handlerThread1.sendEmptyMessage(2);
handlerThread2.sendEmptyMessage(1);
}
}.start();
new Thread()
{
@Override
public void run() {
Looper.prepare();
handlerThread2=new Handler(){
@Override
public void handleMessage(Message msg) {
Log.e("123","121313");
}
};
Looper.loop();
}
}.start();
}
}
应用场景 就是线程之间的通信
HandlerThread = Thread+Looper ;
通信需要 Handler+Looper
主线程自带Looper 所以直接 用Handler就行,子线程 需要借用HanderThread 或者手动写Looper.prepare() 和Looper.loop()