1.什么是Handler
handler通过发送和处理Message和Runnable对象来关联相对应线程的MessageQueue。
1)可以让对应的Message和Runnable在未来的某个时间点进行相应处理;
2)让自己想要处理的耗时操作放在子线程,让更新UI的操作放在主线程。
2.Handler的使用
1)post(runnable)
2)sendMessage(message)
3.内存泄露
1)将Handler设置为静态内部类
2)onDestroy中调用removeCallback
3)Handler内部持有外部activity的弱引用
public class MainActivityextends AppCompatActivity {
private Buttonbutton;
private TextViewtextView;
//1.创建handler,自动绑定到UI线程
// private Handler handler = new Handler();
private Handlerhandler =new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
MainActivity.this.textView.setText("finished");
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.click);
textView = findViewById(R.id.text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MyThread myThread =new MyThread();
myThread.start();
}
});
}
class MyThreadextends Thread {
//post方式
/* @Override
public void run() {
try {
Thread.sleep(5000);
Runnable runnable = new Runnable() {
@Override
public void run() {
MainActivity.this.textView.setText("finished");
}
};
//2.将runnable放到post中,合适的时候执行这个代码(其实底层调用的依旧是sendMessage)
handler.post(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
}*/
@Override
public void run() {
try {
Thread.sleep(5000);
Message message =new Message();
message.what =1;
handler.sendMessage(message);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}