public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_charging);
mHandler.post(runnable);//定期执行
mHandler.postDelayed(runRemove, 9000);//过9秒后执行
}
/** Called when the activity is first created. */
private Handler mHandler = new Handler();
private Runnable runnable = new Runnable(){//推送runnable,定期2s执行一次
@Override
public void run() {
// TODO Auto-generated method stub
SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
Date date = new Date(System.currentTimeMillis());
String time = formatter.format(date);
System.out.println("=============时间"+time);
handler.postDelayed(runnable, 3000);
}
};
private Runnable runRemove = new Runnable(){//移除runnable,在6s后移除
@Override
public void run() {
// TODO Auto-generated method stub
handler.removeCallbacks(runnable);
}
};
}
Android 每三秒执行一次一共执行三次
最新推荐文章于 2024-05-25 11:00:09 发布
该代码段展示了一个Android活动(MainActivity)如何使用Handler和Runnable来执行定时任务。它创建了一个Handler对象,定义了两个Runnable:一个用于每3秒打印当前时间,另一个在9秒后用于移除定时任务。时间格式化为yy-MM-dd-HH-mm-ss。
摘要由CSDN通过智能技术生成