Android Handler Thread HandlerThread
從主線程發送消息到子線程。
子線程必須創建Looper,
handlerThread.getLooper(),
Looper.prepare(),Looper.loop()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button2);
Tthread tthread = new Tthread();
tthread.start();
T3();
T4();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hh.sendEmptyMessage(12);
handler.sendEmptyMessage(12);
handlerT4.sendEmptyMessage(12);
}
});
}
protected void T3() {
HandlerThread handlerThread = new HandlerThread("name-thread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println(Thread.currentThread().getName());
System.out.println("T33333333333333333");
}
};
}
protected void T4() {
Thread thread = new Thread() {
@Override
public void run() {
super.run();
Looper.prepare();
handlerT4 = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("T44444444444444444444");
}
};
Looper.loop();
}
};
thread.start();
}
class Tthread extends Thread {
@Override
public void run() {
super.run();
Looper.prepare();
hh = new HH();
Looper.loop();
}
}
class HH extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("HHHHHHHHHHHHHHHHHHHHHHHH");
System.out.println(Thread.currentThread().getName());
}
}
0 件のコメント:
コメントを投稿