如何在一定次数后停止计时器

时间:2012-07-15 06:39:52

标签: android timer timertask

尝试使用Timer执行此操作4次,每次间隔10秒。

我试过用循环停止它,但它一直在崩溃。尝试使用带有三个参数的schedule(),但我不知道在哪里实现计数器变量。有什么想法吗?

final Handler handler = new Handler(); 
Timer timer2 = new Timer(); 

TimerTask testing = new TimerTask() {
    public void run() { 
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test",
                    Toast.LENGTH_SHORT).show();

            }
        });
    }
}; 

int DELAY = 10000;
for (int i = 0; i != 2 ;i++) {
    timer2.schedule(testing, DELAY);
    timer2.cancel();
    timer2.purge();
}

3 个答案:

答案 0 :(得分:13)

private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
    private int counter = 0;
    public void run() {
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
            }
        });
        if(++counter == 4) {
            timer.cancel();
        }
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timer.schedule(task, DELAY, DELAY);
}

答案 1 :(得分:2)

为什么不使用AsyncTask并在while循环中使用Thread.sleep(10000)和publishProgress?这是它的样子:

new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {

            int i = 0;
            while(i < 4) {
                Thread.sleep(10000);
                //Publish because onProgressUpdate runs on the UIThread
                publishProgress();
                i++;
            }

            // TODO Auto-generated method stub
            return null;
        }
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            //This is run on the UIThread and will actually Toast... Or update a View if you need it to!
            Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
        }

    }.execute();

另外作为旁注,对于长期重复性任务,请考虑使用AlarmManager ...

答案 2 :(得分:1)

for(int i = 0 ;i<4 ; i++){
    Runnable  runnableforadd ;
    Handler handlerforadd ;
    handlerforadd = new Handler();
    runnableforadd  = new Runnable() {
        @Override
        public void run() {
          //Your Code Here
            handlerforadd.postDelayed(runnableforadd, 10000);                         } 
    };
    handlerforadd.postDelayed(runnableforadd, i);

}