答案 0 :(得分:0)
provider = locationManager.getBestProvider(new Criteria(), false);
您为false
参数提供enabledOnly
,因此可能会返回未启用的提供商。然后通过getLastKnownLocation
的javadocs返回null:"如果当前禁用了提供程序,则返回null。"
答案 1 :(得分:0)
您可以使用FusedLocationApi。
代替位置管理员代码示例在这里
protected synchronized void buildGoogleApiClient() {
// Toast.makeText(getContext(), "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
// Log.e("x", mLastLocation.getLongitude() + "");
//Log.e("y", mLastLocation.getLatitude() + "");
currentLocation = mLastLocation;
}
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(5000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(50F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
currentLocation = location;
}
您需要的参数
private GoogleApiClient mGoogleApiClient;
private Location currentLocation;
并在活动或片段onCreateMethode()
上调用buildGoogleApiClient