I\'m working in an application which must send a GPS location every 5 seconds to the server when I choose (auto send button on). I\'m new with android so I don\'t know how I
Look at the AlarmManager class http://developer.android.com/reference/android/app/AlarmManager.html and particularly the setRepeating function. Its going to be a bit more complicated than you'd like though.
Ridcully is right, there is probably no reason to send the current location every 5 seconds. Here is the rational behind that:
You really only care about 2 things about the users location:
Where are they right now?
Have they moved since I got their first location?
So once you get a satisfactory initial location, you can just register to get callbacks whenever the users moves like this:
private LocationListener mLocationListener;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
updateLocation(location);
}
@Override
public void onStatusChanged(final String provider,
final int status, final Bundle extras) {
}
@Override
public void onProviderEnabled(final String provider) {
}
@Override
public void onProviderDisabled(final String provider) {
}
};
}
That being said, you could obviously do what these others have said and run the timer every 5 seconds. The thing is, most good locations take 10-20 seconds to run, so you might only want to run it in that interval. Also FYI, this WILL kill battery
I have faced exactly the same problem, sending location periodically. I've used a handler and its postDelayed
method.
The periodic call part of my code looks like this:
private final int FIVE_SECONDS = 5000;
public void scheduleSendLocation() {
handler.postDelayed(new Runnable() {
public void run() {
sendLocation(); // this method will contain your almost-finished HTTP calls
handler.postDelayed(this, FIVE_SECONDS);
}
}, FIVE_SECONDS);
}
Then you just need to call scheduleSendLocation
when you want to start your period calls.
You can use a Timer
. But I think it would be better if you only send the position of it has changed a certain distance from the last one you sent. This way you'd send way less data without losing any information.