I get location as:
LocationManager locationManager;
GeoPoint p;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (gps_enabled) {
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
However, gps_enabled=true but location =null.
Why can’t get my location? Can you help me?
If i get by NETWORK_PROVIDER is ok.
Well there are a number of things. The GPS could be coming from what’s known as a “cold start” where it doesn’t have any knowledge of where it is. In these cases the last known location is null. You could also be in a location where there is no signal to get a location fix. It could also be a crappy GPS or a crappy GPS driver (cough samsung cough). These things aren’t exact.
First I would start with this documentation. Location Acquisition Strategies
Next, let’s evaluate the logic here. Yes the GPS is enabled. However in this context, enabled means that it is enabled for use by applications with the fine location permission. Enabled does not mean it is currently active and acquiring locations. But there is good news! You can make a listener or subscribe to location updates.
So as others have mentioned, make sure you have the permissions setup in your manifest. I assume you do, or else your app probably crashed and burned with a permission issue on the
getLastKnownLocation()call.Then for receiving location updates, take a look at the LocationListener class. By implementing this interface you can use
locationManager.requestLocationUpdates()to register for location updates from the GPS.Using your code (I assume some things, like it’s within an activity and the method being described is invoked on the UI Thread):
This should run your code as you would expect, and then in the case where the GPS does not have a location, you spin it up and wait until you get a location. Once that occurs you shut it off and use it as you were planning to. This is sort of a naive approach, but you should be able to use it as a simple basis. A real solution should take into account the cases where there is no chance of getting a location, handling the cases when the location provider is not available or becomes unavailable while you are waiting for a location, and validate the sanity of the location.