Handler异步消息处理机制
Android中的异步消息处理主要有4个部分组成Message、Handler、MessageQueue和Looper。
Message:负责线程间传递消息
Handler:用于收发信息
MessageQueue:用于存放消息的队列,每个线程都只有一个该对象
Looper:用于持续监测队列中是否存在消息,将其取出
直接上实例代码
每隔一秒显示一个递增的数字
public class MainActivity extends AppCompatActivity {
private static final int UPDATE=0x1;
private int flag = 0;
private TextView text;
private Handler handler=new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE:
text.setText(String.valueOf(msg.arg1));
break;
}
}
};
private Runnable thread=() -> {
while (true) {
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = UPDATE;
msg.arg1 = flag++;
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
Thread thread1 = new Thread(thread);
thread1.start();
}
}
使用Handler自带定时器也可以完成同样的功能
public class MainActivity extends AppCompatActivity {
private static final int UPDATE=0x1;
private int flag = 0;
private TextView text;
private Handler handler = new Handler();
private Runnable thread= new Runnable() {
public void run() {
handler.postDelayed(this, 1000);
text.setText(String.valueOf(flag++));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
text = (TextView)findViewById(R.id.text);
handler.post(thread);
}
}