Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何修复Timertask只运行一次?_Java_Android_Timer_Timertask - Fatal编程技术网

Java 如何修复Timertask只运行一次?

Java 如何修复Timertask只运行一次?,java,android,timer,timertask,Java,Android,Timer,Timertask,我正在尝试每1秒获取我的当前位置。getlocationCoordinate方法允许返回我当前的纬度和经度 所以我实现了一个timertask,它应该每1秒运行一次并返回我的当前位置,但是timertask只运行一次,我如何解决这个问题 Timer timer= new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Looper

我正在尝试每1秒获取我的当前位置。getlocationCoordinate方法允许返回我当前的纬度和经度

所以我实现了一个timertask,它应该每1秒运行一次并返回我的当前位置,但是timertask只运行一次,我如何解决这个问题

    Timer timer= new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            Looper.prepare();


            System.out.println(" show me current location " + getlocationcoordinate(getApplicationContext()));
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this, "current location" +getlocationcoordinate(getApplicationContext()), Toast.LENGTH_SHORT).show();
                }
            });
            Looper.loop();


        }
    },0,1000);

由于某些原因,计时器不能像我们希望的那样工作,您可以使用处理程序

 private Handler handler;
 private Runnable runnable;


  handler = new Handler();
                handler.postDelayed(runnable, 1000);
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        try{
                            System.out.println(" show me current location " + getlocationcoordinate(getApplicationContext()));
                        }
                        catch(Exception e){
                            e.printStackTrace();
                        }
                        handler.postDelayed(this, 1000); //start again
                    }
                };
来源