Android中 Timer TimerTask Handler的使用举例
package johnny.test.testTimer;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class TestTimerActivity extends Activity {
private int count = 0;
private TextView txv = null;
private Timer timer = null;
private TimerTask timertask = null;
private Handler handler = null;
private Message msg = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialComponment();
timer.schedule(timertask,0,1000); //延迟0毫秒开始执行,每次执行间隔1000毫秒
}
public void initialComponment(){
txv = (TextView)findViewById(R.id.txv);
timer = new Timer();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what==1)
{
txv.setText(""+count);
count++;
}
}
};
timertask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
}
};
}
}