Handler
1.什么是Handler
Handler是Android SDK中处理异步消息的核心类。
Handler的作用是让子线程通过UI线程通信来更新UI界面。
2.什么是Looper和MessageQueue
Android中创建的普通线程默认是没有消息循环的run方法执行完线程也就结束了,那么如何让线程不停的工作呢,这里我们就可以用Looper把普通线程变成可以循环的线程。当创建Looper时,将会自动创建出MessageQueue。需要注意的是一个线程只会存在一个Looper和一个MessageQueue。当MessageQueue中有消息时,Looper将会从MessageQueue中取出消息。
3.什么是Message
Message的英文意思为消息,Message对象即为消息对象,子线程把需要传递到UI线程的消息放到Message对象中,Message对象可以通过Handler对象的obtainMessage方法获得。
what属性:int类型的消息码,接收方用来识别是什么消息。
arg1,arg2属性:int类型,如果传递的消息为数字可以将数字赋给arg1和arg2。
obj属性:Object类型,可以传递任意类型的消息。
如何使用Handler
1.在UI线程中创建Handler匿名内部类对象。
2.在匿名内部类中重写handleMessage方法。
3.在U线程中启动子线程。
4.在线程中获得Message对象。
5.将需要传递的数据赋值到Message对象中。
6.通过Handler对象的sendMessage方法发送消息到消息队列。
7.在handleMessage方法中接收消息。
倒计时案例
我们底下举一个实际的案例来更好的理解Handler。
package com.example.pc.hander;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DaoActivity extends AppCompatActivity {
private Button daojishiBtn;
private EditText daojishiET;
private TextView daojishiTV;
private int time;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
daojishiTV.setText(msg.what+"");
}
//接收
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dao);
bindID();
daojishiBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {//监听
time=Integer.parseInt(daojishiET.getText().toString());//将字符串设置为整形
new Thread(new Runnable() {
@Override
public void run() {
//判断显示数字递减效果
for (int i=time;i>0;i--){
handler.sendEmptyMessage(i);
try{
Thread.sleep(1000);
//停顿一秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
private void bindID() {
daojishiBtn = findViewById(R.id.daojishi_btn);
daojishiET = findViewById(R.id.daojishi_et);
daojishiTV = findViewById(R.id.daojishi_tv);
//赋ID
}
}
<?xml version="1.0" encoding="utf-8"?>
<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.pc.hander.DaoActivity">
<EditText
android:id="@+id/daojishi_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
//输入框
<TextView
android:id="@+id/daojishi_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="倒计时"
android:textSize="20sp"
android:layout_gravity="center"/>
<Button
android:id="@+id/daojishi_btn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="开始倒计时"/>
//按钮
</LinearLayout>