Android中使用Handler的postDelayed(Runnable, long)方法实现定时循环发送数据

时间:2022-02-15 17:32:46

1. 定义一个Handler类

Handler handler=new Handler();  
Runnable runnable=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//要做的事情
handler.postDelayed(this, 5000);
}
};

2. 启动计时器

//每5秒执行一次runnable
handler.postDelayed(runnable, 5000);

3. 停止计时器

 @Override
protected void onDestroy() {
handler.removeCallbacks(runnable);
super.onDestroy();
}