简体   繁体   中英

A new instance of timer created everytime I press a button

I am designing an incrementing clock, which will execute on button click and update the contents of the text view, as in time elapsed. But each time I press this button the previous clock is not getting cleared, a new instance starts and runs in parallel with the previous thread. I am unable to understand as in how do I stop this behavior of the same. Following is my code:

Class level Variables:

 int repeatCounter = 1;
 CountDownTimer tripTimeCounter;

================================================================================

  private View.OnClickListener but = new View.OnClickListener() {

    public void onClick(View v) {
        if (isOnline() == true) {
            tripTimeCounter = new CountDownTimer(60 * 1000, 1000) {

                @Override
                public void onFinish() {
                    // TODO Auto-generated method stub
                    repeatCounter = repeatCounter + 1;

                    this.start();
                    // startTimeCounter();
                }

                @Override
                public void onTick(long millisUntilFinished) {
                    // TODO Auto-generated method stub
                    timedisplay = (TextView) findViewById(R.id.textView3);
                    timedisplay.setText(formatInterval((repeatCounter * 60)
                            * 1000 - millisUntilFinished));

                }

            }.start();
            tripTimeCounter.start();
        } else {
            Toast.makeText(getApplicationContext(),
                    "Not connected to the internet", Toast.LENGTH_LONG)
                    .show();
        }
    }
};

Only skimmed this, but after Googling Timer, saw the cancel method, which says:

When a timer is no longer needed, users should call cancel(), which releases the timer's thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM