如何制止一定的次数后,计时器(How to stop a timer after certain n

2019-06-26 07:10发布

试图用一个Timer做的每10秒的间隔运行这个4倍。

我试图用循环停止,但它总是崩溃。 使用试过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();
}

Answer 1:

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


Answer 2:

为什么不使用AsyncTask ,只是有它的Thread.sleep(10000)和publishProgress在while循环? 下面是它会是什么样子:

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 ...



Answer 3:

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

}


文章来源: How to stop a timer after certain number of times