1

我想在地图上显示位置。但是每次我重新安装该应用程序时,它都会要求两次位置许可,这是我第一次启动该应用程序时。

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    LatLng googleHeadquater = new LatLng(37.421949, -122.084261);
    mMap.addMarker(new MarkerOptions().position(googleHeadquater).title("Google Headquater"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(googleHeadquater, 16));

    //mMap.setOnMyLocationButtonClickListener(this);
    enableMyLocation();
}

private void enableMyLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
    } else if (mMap != null) {
        // Access to the location
        mMap.setMyLocationEnabled(true);
    }
}

显现

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

获取位置:

protected synchronized void builGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}
@Override
public void onConnected(Bundle bundle ) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setFastestInterval(3000); // 3 second
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}

在请求许可后,它不会更新位置,除非我去另一个活动并回来。

4

0 回答 0