Java 如何修复Timertask只运行一次?
我正在尝试每1秒获取我的当前位置。getlocationCoordinate方法允许返回我当前的纬度和经度 所以我实现了一个timertask,它应该每1秒运行一次并返回我的当前位置,但是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
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
}
};
来源