如何停止定时器任务

how can to stop timer task

我有一个计时器和计时器任务和处理程序以及可运行的 我的代码每 10 秒执行一次,直到 ServerResponse 变量不为空,然后重定向到另一个 activity.

但是当我的代码重定向到另一个 activity 计时器任务时正在运行 !!!!!

当我们在另一个activity时如何停止定时器任务??

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    new sendDataToServer().execute();
                    final Handler handler = new Handler();

                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            if(serverResponse.length() > 0)
                            {
                                Intent intent = new Intent(PayementActivity.this,UserFormActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                    }, 10000);
                }
            });
        }
    }, 0, 10000);
       Timer timer = new Timer();
        timer.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    new sendDataToServer().execute();
                    final Handler handler = new Handler();

                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            if(serverResponse.length() > 0)
                            {
                                Intent intent = new Intent(PayementActivity.this,UserFormActivity.class);
                                if(timer!= null) {
                                timer.cancel();
                                timer.purge();
                                timer= null;
    }
                                startActivity(intent);
                                finish();
                            }
                        }
                    }, 10000);
                }
            });
        }
    }, 0, 10000);

这可能不会直接回答您的问题,但响应式扩展是使用 TimerTasks 的一个很好的替代方法。检查 this and this

subscription = Observable.interval(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())// Runs on a io thread pool
                .observeOn(AndroidSchedulers.mainThread()) // Observes on UI thread 
                .subscribe(timeCount ->{
                    // Your code here
                 });
subscription.unsubscribe();// Stops the stream.