1、使用TimerTask定时开始周期性执行某个动作
scheduleAtFixedRate(TimerTask
task, long delay, long period)
Schedule a task for repeated fixed-rate execution after a specific delay has passed.
Parameters
task | the task to schedule. |
---|---|
delay | amount of time in milliseconds before first execution. |
period | amount of time in milliseconds between subsequent executions. |
java代码:
//周期性的上传速度 Timer timer = new Timer(); TimerTask timerTask=new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Log.i(TAG, "平均速度为"); } }; timer.scheduleAtFixedRate(timerTask, 0, 5000); }
2、使用Handler
//初始化为了全局使用 Handler handler=null; Runnable update=null; ------------------------------------- try{ handler=new Handler(); update=new Runnable() { @Override public void run() { // TODO Auto-generated method stub // do sth handler.postDelayed(update, 1000); //1秒后将再次调用 } }; handler.post(update); //真正开始的指令; handler.removeCallbacks(update);//停止指令
Done!