我知道有几个问题已经被要求,我尝试了一些答案,但它不适用于我。getLastKnownLocation一直返回null
我已经为两个位置服务添加了权限,但它持久地返回null。
这是我的Java code。
我知道有几个问题已经被要求,我尝试了一些答案,但它不适用于我。getLastKnownLocation一直返回null
我已经为两个位置服务添加了权限,但它持久地返回null。
这是我的Java code。
provider = locationManager.getBestProvider(new Criteria(), false);
你的enabledOnly
参数提供false
,所以它可能是返回未启用的供应商。然后通过javadocs返回getLastKnownLocation
它将返回null:“如果提供程序当前被禁用,则返回null。”
除了位置管理器,您可以使用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;
,并呼吁buildGoogleApiClient上的活动或片段onCreateMethode()
你的建议我应该enabledOnly值更改为真?我试过了。也不起作用。 –