Handler
- 为什么要用Handler
- 什么是Handler
- 什么是Looper
- 什么是MessageQueue
- Handler怎么用
- 案例解析——倒计时Demo
为什么要用Handler
- UI线程不能做耗时操作。
- 子线程无法更新UI。
什么是Handler
Handler是Andorid SDK中处理异步消息的核心类。Handler的作用是让子线程通过与UI线程通信来更新UI界面。
什么是Looper
在Android中创建出的普通线程默认是没有消息循环的,润run方法执行完毕,线程也就结束了。
如果让线程不停的循环工作时,可以使用Looper,将普通线程变成循环工作的线程。
什么是MessageQueue
当创建Looper时,将会自动创建出MessageQueue。
一个线程中只会存在一个Looper和MessageQueue。
当MessageQueue中有消息时,Looper将从MessageQueue取出消息。
Handler怎么用
handler.sendEmptyMessage(1);
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
daojishi_tv.setText("更新UI后你想显示的内容");
}
};
案例解析——倒计时Demo
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity"
android:orientation="vertical">
<TextView
android:id="@+id/daojishi_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
<Button
android:id="@+id/daojishi_but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始倒计时"
android:layout_gravity="center"
/>
</LinearLayout>
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
private TextView daojishi_tv;
private Button daojishi_but;
int count=10;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
daojishi_tv.setText(msg.what+"");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
bindID();
}
private void bindID() {
daojishi_tv=findViewById(R.id.daojishi_tv);
daojishi_but=findViewById(R.id.daojishi_but);
daojishi_but.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.daojishi_but:
new Thread(new Runnable() {
@Override
public void run() {
while (count>0) {
handler.sendEmptyMessage(count);
count--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
break;
}
}
}