Android: Timer Task query

℡╲_俬逩灬. 提交于 2019-12-24 08:39:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!