问题
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);
}
回答1:
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);
}
来源:https://stackoverflow.com/questions/15922813/android-timer-task-query