Android: Timer任务查询



我有一个应用程序,其中基于一些点击,我使用TimerTask()启动定时器。但我也希望有支持多个定时器多次点击。因此,如果一个计时器已经在工作,另一个点击发出,那么它将启动一个单独的计时器线程,而不仅仅是取消第一个。

有人能帮帮我吗?

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

你可以这样写:

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

最新更新