android Timer使用方法

Timer属性:http://www.apihome.cn/api/java/Timer.html

声明创建:

 private Timer mTimer;

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
timer = new Timer();
timer.schedule(task, 1000, 5000);
} TimerTask task = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}; final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
log.e("Timer", "Timer");
//要实现的功能代码:update();
break;
}
super.handleMessage(msg);
}
}; protected void onDestroy() {
if (timer != null) {
timer.cancel();
timer = null;
}
super.onDestroy();
}

最重要的一点是 timer.schedule(task,1000,5000),如果设置为 timer.schedule(task,5000)是不会工作的。
因为timer.schedule(task,5000) 是表示执行一次的任务。
timer.schedule(task,1000,5000)表示 1 秒钟后开始 5 秒钟为周期 重复执行

     private Handler handler = new Handler( );

     private Runnable runnable = new Runnable( ) {

     public void run ( ) {

        update( );

        handler.postDelayed(this,1000);     //postDelayed(this,1000)方法安排一个Runnable对象到主线程队列中

       }

     };

     handler.postDelayed(runnable,1000);         // 开始Timer

     handler.removeCallbacks(runnable);           //停止Timer

(转自:http://blog.csdn.net/jincf2011/article/details/6603916)

上一篇:APP并非一个人在战斗,还有API—Xamarin.Android回忆录


下一篇:Xamarin.Android之SQLiteOpenHelper