Handler.PostDelayed(可运行,时间)不会停止

时间:2017-10-21 17:31:02

标签: java android multithreading

在我的代码中,我需要每隔5秒调用一些函数(例如),当我再次按下按钮时我需要暂停runnable但不起作用,因为在日志中我一直在读取可运行的静止再次打电话给方法。

   //Listner for button that search location for travel
    startMonit.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            final Handler handler = new Handler();
            Runnable runnable = null;


            if (startMonit.getText().toString().equals("MONITORIZZA")) {

                Log.i(TAG,"dentro equals Monitorizza");
                startMonit.setText("STOP");
                runnable = new Runnable() {
                    public void run() {
                        Log.i(TAG, "run Handler post delayed");
                        getUserLocation(true); //true because i have travel coordinates and i need to monitorate travel distance
                        //getDistanceTime(travelInfo);

                        handler.postDelayed(this, 5000); //now is every 2 minutes
                    }
                };

                handler.postDelayed(runnable, 5000); //Every 120000 ms (2 minutes)

            }else {
                Log.i(TAG,"dentro equals non monitorizza");
                startMonit.setText("MONITORIZZA");
                //Rimuovo il thread che monitorizza
                handler.removeCallbacks(runnable);
            }

        }

    });

这个代码我哪里错了?

0 个答案:

没有答案