Are you talking about the location.getLongitude()
call outside of the callback?
If that is what you are talking about, then there is no guarantee that a phone will have GPS or have GPS enabled. In either of those scenarious, you'll get a null response. While it is hard to cater for all scenarios, you're better off getting location from the network provider which is very likely to be there. Also, I would use a Criteria
builder to get a connection more suited for your needs. For example, if you just want to know what city a user is in, GPS is over kill.
//force last known location from network provider
String providerName = LocationManager.NETWORK_PROVIDER;
if (mLocationManager.isProviderEnabled(providerName)) {
Location lastLocation = mLocationManager.getLastKnownLocation(providerName);
}
//get high accuracy provider
providerName = mLocationManager.getBestProvider(createMediumCriteria(), true);
if (providerName == null) {
// get low accuracy provider
providerName = mLocationManager.getBestProvider(createLowCriteria(), true);
}
if (providerName == null) {
//get low accuracy even if its disabled
providerName = mLocationManager.getBestProvider(createLowCriteria(), false);
}
if (providerName != null && mLocationManager.isProviderEnabled(providerName)) {
Location lastLocation = mLocationManager.getLastKnownLocation(providerName);
if (lastLocation != null) {
onLocationChanged(lastLocation);
}
//else {
//timeout after 30 seconds.
if (!sLocationHandler.hasMessages(MSG_UNREGISTER)) {
sLocationHandler.sendEmptyMessageDelayed(MSG_UNREGISTER, 30000);
}
//LocationProvider provider = locMgr.getProvider(providerName);
// using low accuracy provider... to listen for updates
mLocationManager.requestLocationUpdates(providerName, 0, 0f, this);
//}
The criteria builders will be something like:
/**
* this criteria will settle for less accuracy, high power, and cost
*/
public static Criteria createLowCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_LOW);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_LOW);
return c;
}
/**
* this criteria needs high accuracy, high power, and cost
*/
public static Criteria createMediumCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_MEDIUM);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}