Android中实现定时周期任务的方法

本文介绍几种Android中实现定时周期任务的方法.

1.Timer

Timer timer = new Timer( );

TimerTask task = new TimerTask( ) {

public void run ( ) {

//如果不需要操作UI则可以省略handler的部分直接在定时器里完成业务逻辑

doSth( );

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");

updateUI( );

break;

}

super.handleMessage(msg);

}

};


protected void onDestroy ( ) {

if (timer != null) {

timer.cancel( );

timer = null;

}

super.onDestroy( );

}

/********

*需要启动定时器时调用如下即可

* timer.schedule(task,delaytime,period); //delaytime表示多久后开始执行,period为周期,如果不需要重复可省略第三个参数ms为单位)

*******/




2. Handler + Runnable线程

private Handler handler = new Handler( );

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

private Runnable runnable = new Runnable( ) {

public void run ( ) {

doSth( );

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

}

};

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

你可能感兴趣的:(Android,Note)