无论我做什么,我都无法在没有启用wifi的情况下获得当前位置。此代码仅在启用wifi时有效:
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
provider = LocationManager.GPS_PROVIDER;
else if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
provider = LocationManager.NETWORK_PROVIDER;
else if(locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER))
provider = LocationManager.PASSIVE_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
禁用wifi时,location
为空。
以下代码永远不会工作(即使启用了wifi):
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
onCreate()
中的:
buildGoogleApiClient();
onStart()
中的:
mGoogleApiClient.connect();
这里onConnected()
:
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation == null)
{
disableButtons();
}
else
{
String userLocation = FindLocation.getLocatoinName(mLastLocation);
userLocationDetails = new LocationStruct(mLastLocation.getLatitude(), mLastLocation.getLongitude(), userLocation);
}
}
在onConnected()
内,mLastLocation
始终为空。
我尝试了2部手机:联想A820 API 16 和三星Galaxy S4 API 19 。两部手机都有相同的结果。
答案 0 :(得分:1)
您不能依赖最后一个位置始终可用。
在您的onConnected()
中,您只需检查上一个已知位置。
您必须在LocationRequest
onConnected()
mLocationRequest = LocationRequest.create()
.setPriority(locationPriority) // LocationRequest.PRIORITY_HIGH_ACCURACY
.setInterval(10 * 1000) // 10 * 1000 10 seconds, in milliseconds
.setFastestInterval(1 * 1000);
然后您必须请求位置更新:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
然后,您将获得onLocationChanged(Location location)