theapache64 theapache64 - 9 days ago 5
Java Question

Android Get Location

I want to get the user location through GPS, if the GPS can't connect to the satellite within 30 seconds then I want to get the location through

LocationManager.getLastKnownLocation()
.

I can do both the work (i.e. get the location through GPS and from last known location), but I don't know how to do this using a timer (i.e. within 30 seconds). I heard that it can be done by using
Handler
s or Java
Timer
class. But I can't understand that.

Answer

Set a boolean gotLocation = true when you get the location from GPS:

public void onLocationChanged(Location location){
    if(location != null){
        gotLocation = true;
    }
}

And when you make your request like requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

add below a Handler with 30 seconds of delay like this:

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if(!gotLocation){
                // get your last known location...
            }
        }
}, 30000);
Comments