每隔一段时间调用一个方法,并在Android中的某个条件下停止调用它

时间:2017-05-24 21:05:10

标签: java android

我在Android的Java类中有一个名为check的方法,我使用以下方法每隔30秒调用一次。我的问题是,当名为stopFlag的变量等于1但我无法使用timer.cancel()执行此操作时,我想停止调用它。

这是我的方法:

 public void callAsynchronousTask() 
{
        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {

                        try {
                            check(currentDistance);
                        } catch (Exception e) {
                            Log.e(TAG,e.getMessage());
                        }
                    }
                });
            }
        };
        if( stopFlag==1){
            timer.cancel();
            timer.purge();
            return;
        }
        else
            timer.schedule(doAsynchronousTask, 0, 30000); //execute in every 30000 ms
    }

//检查方法

public void check(double oldDistance)
    {
        currentDistance=measureDistance(myLoc.getLatitude(),myLoc.getLongitude(),RetrieveStationId.getStation_lat(),RetrieveStationId.getStation_lon());
        if(currentDistance>=0 && currentDistance <200)
        {
            Log.e("Diff",Double.toString(oldDistance-currentDistance));
            joined=0;
            Join.setBackgroundResource(R.drawable.circle_button);

            StateListDrawable drawable = (StateListDrawable) Join.getBackground();
            drawable.setColorFilter(Color.rgb(238,238,238),PorterDuff.Mode.MULTIPLY);
            updateMarker();updateCamera();
            stopFlag=1;
        }
        else if(oldDistance-currentDistance>0)
        {
            Log.e("Diff",Double.toString(oldDistance-currentDistance));
            joined=1;
            Join.setBackgroundResource(R.drawable.circle_button);

            StateListDrawable drawable = (StateListDrawable) Join.getBackground();
            drawable.setColorFilter(Color.rgb(100,100,100),PorterDuff.Mode.MULTIPLY);
        }
        UpdateLocation updateLocation = new UpdateLocation(this);
        updateLocation.execute(latitude, longitude,iden,Integer.toString(request),destination,Integer.toString(joined));
        updateMarker();
        updateCamera();

    } 

0 个答案:

没有答案