How to stop a timer after certain number of times

后端 未结 3 824
醉话见心
醉话见心 2021-01-12 04:06

Trying to use a Timer to do run this 4 times with intervals of 10 seconds each.

I have tried stopping it with a loop, but it keeps crashing. Have tried

3条回答
  •  春和景丽
    2021-01-12 04:50

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

提交回复
热议问题