getLastKnownLocation保持返回null

时间:2017-07-24 14:48:36

标签: android

我知道有几个问题已被要求,我尝试了一些答案,但它对我不起作用。

我已为两个位置服务添加了权限,但它一直返回null。

这是我的Java code

2 个答案:

答案 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