I'm trying to write an Android app that gets the current location from the 'network' provider (so I should only need the android.permission.ACCESS_COARSE_LOCATION
permission). This works fine on some devices, but on others I don't seem to be able to get a location update. Here's my code.
In onCreate:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = LocationManager.NETWORK_PROVIDER;
Log.v (TAG, "Finding location from provider: " + provider);
if (CHECK_PROVIDER_ENABLED && !locationManager.isProviderEnabled (provider))
{
Toast.makeText (this, "Location provider disabled", Toast.LENGTH_LONG).show ();
}
else
{
try
{
Location location = locationManager.getLastKnownLocation(provider);
if (location == null)
{
Log.i (TAG, "getLastKnownLocation returned null, requesting updates when available");
locationManager.requestLocationUpdates (provider, 0, 0, locationListener);
}
else
locationListener.onLocationChanged (location);
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Failed to get location from provider " + provider, e);
Toast.makeText (this, "Location provider disabled", Toast.LENGTH_LONG).show ();
}
}
locationListener is defined as follows:
private LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged (String provider, int status, Bundle extras)
{
}
@Override
public void onProviderEnabled (String provider)
{
}
@Override
public void onProviderDisabled (String provider)
{
}
@Override
public void onLocationChanged (Location location)
{
Toast.makeText (CarouselViewerActivity.this, "" + location.getLatitude () + ", " + location.getLongitude (), Toast.LENGTH_LONG).show ();
Log.v(TAG, "" + location.getLatitude () + ", " + location.getLongitude ());
locationManager.removeUpdates (this);
}
};
On phones that work, everything here works fine: if CHECK_PROVIDER_ENABLED is true, the isProviderEnabled
test returns true, getLastKnownLocation
returns a location rather than null, and if I force the request for updates I receive one with details of a location.
But on other phones (the specific one I'm testing with is a Galaxy S2 with Cyanogenmod 9) the isProviderEnabled
test returns false (despite the settings item for enabling network location being turned on - see LocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) is not reliable, why? for a summary of this issue), getLastKnownLocation
returns null, and after requesting updates I do not receive one in a reasonable time (I've waited 5 minutes).
Is there something wrong with the approach I'm taking? Is there some other way of getting the network location I need, or some setting on the phone other than enabling network location that's required for this to work? At a more basic level, what exactly is going wrong here?