Reputation: 434
I am trying to get my current location each 1 second. The method getlocationCoordinate allows to return my current lattitude and longitude.
So I implemented a timertask that is supposed to run every 1 second and return my current location, but the timertask is only running once, how can i fix this problem?
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);
Upvotes: 1
Views: 86
Reputation: 172
for some reason timer does not work as we would like,You can use a Handler
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
}
};
source here
Upvotes: 1