Handler使用详解
1. 简单实现
1.1 基础知识
- void handleMessage(Message msg); 处理消息的方法,通常是用于被重写!
- sendEmptyMessage(int what); 发送空消息
- sendEmptyMessageDelayed(int what,long delayMillis); 指定延时多少毫秒后发送空信息
- sendMessage(Message msg); 立即发送信息
- sendMessageDelayed(Message msg); 指定延时多少毫秒后发送信息
- final boolean hasMessage(int what); 检查消息队列中是否包含what属性为指定值的消息 如果是参数为(int what,Object object):除了判断what属性,还需要判断Object属性是否为指定对象的消息
1.2 计时器实战
- 页面布局activity_main.xml
<?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:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35dp"
android:id="@+id/tv_test"/>
</LinearLayout>
- 主页面MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView tv_test;
String test[] = new String[]{
"1", "2", "3", "4", "5", "6", "7", "8", "9"
};
int numStart = 0;
Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 0x123) {
tv_test.setText(test[numStart++%9]);
Log.d("MainActivity", "numStart:" + numStart);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
new Timer().schedule(new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0x123);
}
},0,1000);
}
private void initView() {
tv_test = (TextView) findViewById(R.id.tv_test);
}
}