如何取消TimerTask的为AsyncTask的android系统 [英] How to cancel timerTask for AsyncTask in android

查看:225
本文介绍了如何取消TimerTask的为AsyncTask的android系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我工作的TCP套接字。
我能为每1秒读取数据。实现它,我用的TimerTask,如下面的code。

Hi I am working on TCP socket. I can read data for every 1 sec. to achieve it I used TimerTask as shown in below code.

Handler handler = new Handler();
Timer timer = new Timer();

TimerTask doAsynchronousTask = new TimerTask() {

        @Override
        public void run() {
            finalizer = new Runnable() {
                public void run() {
                    try {
                        if (navBool) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    new RetriveStock().execute(); // AsyncTask.
                                }
                            });

                        }
                    } catch (Exception e) {
                    }
                }
            };
            handler.post(finalizer);
        }
    }; 
timer.schedule(doAsynchronousTask, 0, 1000);

有关取消此计时器我用code作为

For canceling this timer I used code as

timer.cancel();
timer = null;
handler.removeCallbacks(finalizer);

但它不取消计时器。我不知道为什么。

But it is not cancelling the timer. I do not know why.

推荐答案

timer.cancel(),你应该取消分配给该任务计时器( doAsynchronousTask 你的情况)。因为多个TimerTasks可以分配给一个定时器,主叫 timer.cancel()不会与当前运行的任务干扰

Instead of calling timer.cancel(), you should be canceling the task that is assigned to that timer (doAsynchronousTask in your case). Since multiple TimerTasks can be assigned to one timer, calling timer.cancel() will not interfere with a currently running task.

定时器的JavaDoc

公共无效取消()

终止此计时器,丢弃所有当前已安排的任务。是否
  不与当前正在执行的任务干扰(如果存在)。一旦
  计时器已终止,它的执行线程终止优雅,
  并没有更多的任务可能安排在了。

Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

这篇关于如何取消TimerTask的为AsyncTask的android系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆