Android 中 Timer 和 TimerTask的使用

Android中Timer是一个普通的类,其中有几个重要的方法;而TimerTask则是一个抽象类,其中含有一个抽象方法run()。

使用Timer类中的schedule()方法可以完成对TimerTask的调度,该方法具有三个参数,其函数声明如下:

public void schedule(TimerTask task, long delay, long period)

其中第一个参数为TimerTask的对象,通过实现其中的run()方法可以周期的执行某一个任务;第二个参数表示延迟的时间,即多长时间后开始执行;第三个参数表示执行的周期。

多个TimerTask是可以共用一个Timer的,通过调用Timer的schedule方法可以创建一个线程,并且调用一次schedule后TimerTask是无限的循环下去的,使用Timer的cancel()停止操作。当同一个Timer执行一次cancle()方法后,所有Timer线程都被终止。

这里为了验证Timer和TimerTask的用法,举了一个案例进行验证,其源代码如下所示:

package com.glemontree.timetaskdemo;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
private int secondLeft = 6;
private TextView textView;
Timer timer = new Timer();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.texttime);
}

public void begin(View view) {
    timer.schedule(task, 1000, 1000);
}

TimerTask task = new TimerTask() {
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        runOnUiThread(new Runnable() {
            
            @Override
            public void run() {
                // TODO Auto-generated method stub
                secondLeft--;
                textView.setText("" + secondLeft);
                if (secondLeft < 0) {
                    timer.cancel();
                    textView.setText("倒计时结束");
                }
            }
        });
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

上面这段代码需要注意的是由于改变UI只能在主线程中进行,因此调用了runOnUiThread方法运行在主线程。

你可能感兴趣的:(Android 中 Timer 和 TimerTask的使用)