什么是Handler
1.概念
Handler是Android SDK中处理异步消息的核心类。
2.作用
Handler的作用是让子线程通过与UI线程通信来更新UI界面
3.Handler对象的常用方法
sendEmptyMessage();sendMessage();obtainMessage();Post();postDelayed();
为什么要用Handler
因为臣妾做不到啊!(在每个Android应用启动时,这个应用汇启动一个UI线程,只有在UI线程里才可以对控件、布局进行获取或设置。也就是主线程不允许做耗时操作,子线程不允许更新UI)所以我们就需要信息机制——Handler。将子线程的消息传递给主线程,再由主线程来执行消息内容。
什么是Looper和MessageQueue
Looper就相当于是Handler消息机制里的传递员,MessageQueue相当于是Handler消息机制里的容器。
当子线程需要做某个操作时,子线程将消息发送到MessageQueue中,再由Looper将消息取出,传递给主线程执行。
什么是Message
消息对象,子线程将需要传递到UI线程的信息放入Message对象中,Message对象可以通过Handler对象的ObtainMessage方法获取。
message对象有三个属性(what属性,arg1、arg2属性,obj属性),一个方法(sendToTarget方法)
如何使用Handler
1.在UI线程中创建Handler匿名内部类对象
2.在匿名内部类中重写handlerMessage方法
3.在UI线程中启动子线程
4.在线程中获得Message对象
5.将需要传递的数据赋值到Message对象中
6.通过Handler对象的sendMessage方法发送消息到消息队列
7.在handlerMessage方法中接收消息
倒计时案例举例
代码展示
XML代码
<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"
android:orientation="vertical"
tools:context="com.example.administrator.handlerdemo.Main2Activity">
<EditText
android:id="@+id/shijian_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/daoshu_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="倒计时:"
android:textSize="30sp"/>
<Button
android:id="@+id/jishi_btn"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="开始计时"
android:layout_gravity="center"/>
</LinearLayout>
Java代码
public class Main2Activity extends AppCompatActivity {
private EditText shijianET;
private TextView daoshuTV;
private Button jishiBtn;
private int time;
private Handler handler= new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
daoshuTV.setText(msg.what+"");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
bindID();
jishiBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
time = Integer.parseInt(shijianET.getText().toString());
new Thread(new Runnable() {
@Override
public void run() {
for (int i =time;i>=0;i--){
Message message = handler.obtainMessage();
message.what = time;
handler.sendEmptyMessage(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
private void bindID() {
shijianET = findViewById(R.id.shijian_et);
daoshuTV = findViewById(R.id.daoshu_tv);
jishiBtn = findViewById(R.id.jishi_btn);
}
}