【问题标题】:How to stop the handler which running on interval (1 min)?如何停止间隔(1分钟)运行的处理程序?
【发布时间】:2016-07-23 20:13:10
【问题描述】:

我正在开发一个应用程序,在该应用程序中,我每隔一分钟将设备位置发送到服务器。我在这里使用 Handler 来安排我的任务。用户单击 STOP 按钮后,处理程序应停止执行。我无法做到这一点。请在下面找到我的代码。

    public void callSpecficTime() {

    timer = new Timer();
    doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {

            handler.post(new Runnable() {
                public void run() {
                    try {
                        Log.e("TImeOnSchedule", String.valueOf(inTime));
                        if(inTime==5)
                        {
                             new PostDataAsyncTask().execute();
                         }


                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 60000);
}

StopTask 代码:

    public void stopTask(){

    if(doAsynchronousTask!=null){
        Log.d("TIMER", "timer canceled");
        handler.removeCallbacks(doAsynchronousTask);
     // timer.cancel();
        doAsynchronousTask.cancel();
    }

}

我试过stopService,removeCallbacks,但没用。谁能为此提供解决方案?

更新

 public void onClickButton(View v)
{
    if(v.getId()==R.id.IBstart)
    {
        callAsynchronousTask();
        callSpecficTime();
    }
    else if(v.getId()==R.idIBstop)
    {
       stopTask();
    }
}

这是** callAsynchronousTask()**

 public void callAsynchronousTask() {
    new PostDataAsyncTask().execute();
}

我发布了两次数据。第一次是用户单击 START 按钮,然后我启动计时器以每分钟执行一次。

【问题讨论】:

    标签: android performance android-handler android-runonuithread


    【解决方案1】:

    cancel()之后使用purge()

    public void stopTask(){
    
        if(doAsynchronousTask!=null){
            Log.d("TIMER", "timer canceled");
            handler.removeCallbacks(doAsynchronousTask);
         // timer.cancel();
            doAsynchronousTask.cancel();
            doAsynchronousTask.purge();
        }
    
    }
    

    【讨论】:

    • time.purge() 对吗?我这样做了。问题还是一样。我得到doAsynchronoursTasknull
    【解决方案2】:
    1. 您应该首先停止 TimerTask:Timer.Cancel()Timer.Purge()
    2. 您可以将:handler.removeCallbacks(doAsynchronousTask); 更改为 removeCallbacksAndMessages(null)

    编辑:

    查看您的日程安排代码:timer.schedule(doAsynchronousTask, 0, 60000); --> 这意味着您立即开始您的 task,并在 60 秒后重复。
    当我看到您的 onClickButton 监听器时,有 2 个任务将立即执行。结果,您无法取消已执行的任务。为了避免它,您可以致电:timer.schedule(doAsynchronousTask, 60000, 60000);

    【讨论】:

    • 我试过了...它还在运行...` public void stopTask(){ timer.cancel();计时器.purge(); // new PostDataAsyncTask().cancel(true); handler.removeCallbacksAndMessages(null); }`
    • 你在哪里调用 callSpecficTime()?
    • 当用户点击 UI 中的 START 按钮时
    • 你有解决这个@Kingfisher Phuoc的办法吗
    • @AnishKumar 你能把你所有的代码贴出来吗,也许问题出在另一块代码上,不要停止,开始一个。
    猜你喜欢
    • 2021-11-12
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2013-02-11
    • 2021-06-13
    相关资源
    最近更新 更多