Search code examples
androidgpslocationmanager

Android get location from GPS


My situation is like that the user has their tablet with them all day and its gps or location can be turned off whole time to save battery, and then wanna post something using my application which requires them to turn on the location and then upon posting I wanna get the latitude and longitude of the device. Using LocationManager when I get the location its null. Any help would be appreciated.

I'm using the below code to get the location:

LocationManager lm = (LocationManager)ctx.getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

As I've checked around, it seems I have to put a listenere to update the device location so when I get the last known location it wouldn't be null, but how can I do that if the device's location is off before using the application? I wanna get the location where the user is posting using the application.

EDIT: I've changed my code to below, but loc is always null and loc2 always returns location. why is that?

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location loc2 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

and this is the listener:

LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void onProviderEnabled(String provider) {

    }

    public void onProviderDisabled(String provider) {

    }
};

Solution

  • You might want to consider using Network Location as well as GPS Location, as many users just keep the GPS radio off to conserve battery. With Location Services set in "Battery Saving" mode, the device can get accurate geo-location data using Wi-Fi if available.
    If you use Network Location data as well as GPS radio data, you would have a much better chance of getting location data when you need it.

    However, if Location Services were disabled completely prior to being turned on in order to post something using your app, then you would need to register a Location Listener to get the first instance of location data.

    Take a look at this post to see how to use both Network and GPS Location: Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location