我试图每1秒获取一次我的当前位置。方法getlocationCoordinate允许返回我当前的经度和纬度。
因此,我实现了一个应该每1秒运行一次并返回我当前位置的timertask,但是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);
答案 0 :(得分:1)
由于某些原因,计时器无法正常运行,您可以使用处理程序
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
}
};
来源here