您是否在談論回撥以外的location.getLongitude()
通話? 如果這是你正在談論的,那麼不能保證手機將具有GPS或啓用GPS。在任何一個場景中,你都會得到一個空的迴應。雖然很難滿足所有情況,但最好從網絡提供商那裏獲得位置,這很可能在那裏。另外,我會使用Criteria
構建器來獲得更適合您需求的連接。例如,如果您只想知道用戶在哪個城市,GPS就會被殺死。
//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);
//}
的標準建設者將是這樣的:
/**
* 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;
}
來源
2015-04-06 13:14:24
Ali
似乎無法確定lastKnownLocation,所以它給了你'null',因此你可以使用任何'Location'方法,直到你真正得到一個可能重複的[Location Manager Returns Null Pointer Expection]的Location [ – gtgaxiola 2015-04-06 13:08:16
]( http://stackoverflow.com/questions/23971333/location-manager-returns-null-pointer-expection) – gtgaxiola 2015-04-06 13:09:24
添加一些日誌,以便它會更好地理解。 – 2015-04-06 13:10:22