Sunny
Sunny

Reputation: 7614

Android: Timer Task query

I have an app in which based on some click I start the timer using the TimerTask(). But I would also like to have support for multiple timers for multiple clicks. So if one timer is already working and another click is issued then it starts a separate timer thread and not just cancel the first one.

Could someone please help?

@Override
public void onListItemClicked(int index, Map<String, Object> data) {
    timer = new Timer();
    timer.schedule(new TimerTask() {
         int n = 0;
         @Override
         public void run() {        
             if (++n == 300) {
                 timer.cancel();
             }
             timer = null;
         }
    },1000,1000);
}

Upvotes: 1

Views: 1279

Answers (1)

Krypton
Krypton

Reputation: 3325

You can have things like this:

@Override
public void onListItemClicked(int index, Map<String, Object> data) {
    //you shouldn't have timer as class' property
    //if so your timer will cancel itself when you click again
    //local timer will be cancelled  when n is counted to 300 only
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        int n = 0;
        @Override
        public void run() {

            if (++n == 300) {
                timer.cancel();
            }
            timer = null;
        }
    },1000,1000);
}

Upvotes: 2

Related Questions