LocationServices.SettingsApi deprecated

2019-01-27 18:47发布

My code is:

if (mGoogleApiClient == null && checkGooglePlayService()) {
        Log.d(Utils.TAG_DEV + TAG, "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);
        mLocationSettingsRequest = builder.build();
        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(
                        mGoogleApiClient,
                        mLocationSettingsRequest
                );
        result.setResultCallback(this);

    }

but unfortunately the LocationServices.SettingsApi is deprecated. How can I replace deprecated code with the new one?

I found reading docs that the solution can be to use SettingsClient but couldn't figure how to do it.

Any ideea what to do to can update my code?

2条回答
够拽才男人
2楼-- · 2019-01-27 19:15

LocationServices.SettingsApi deprecated

Yes, LocationServices.SettingsApi is deprecated

How can I replace deprecated code with the new one?

You need to use GoogleApi-based API SettingsClient

FROM DOCS

SettingsClient

public class SettingsClient extends GoogleApi<Api.ApiOptions.NoOptions>

The main entry point for interacting with the location settings-enabler APIs.

This API makes it easy for an app to ensure that the device's system settings are properly configured for the app's location needs.

When making a request to location services, the device's system settings may be in a state that prevents an app from obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched off. This intent makes it easy to:

  • Determine if the relevant system settings are enabled on the device to carry out the desired location request.

  • Optionally, invoke a dialog that allows the user to enable the necessary location settings with a single tap.

I found reading docs that the solution can be to use SettingsClient but couldn't figure how to do it.

Follow this steps

To use this API, first create a LocationSettingsRequest.Builder and add all of the LocationRequests that the app will be using:

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
     .addLocationRequest(mLocationRequestHighAccuracy)
     .addLocationRequest(mLocationRequestBalancedPowerAccuracy)

Then check whether current location settings are satisfied:

Task<LocationSettingsResponse> result =
         LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
查看更多
何必那么认真
3楼-- · 2019-01-27 19:19

I use this code after deprecation of LocationServices.SettingsApi an FusedLocationApi

This code provides :

1) Request last location

2) Location update periodically with FusedLocationProviderClient

All codes in your Activity

private FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    //ADD THIS LINE
    mFusedLocationClient  = LocationServices.getFusedLocationProviderClient(this);
    buildGoogleApiClient();
    createLocationRequest();
    Loc_Update();
    //...
}



protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                            @Override
                            public void onSuccess(Location location) {
                                if (location!=null){
                                    LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
                                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
                                }
                            }
                        });
                    }
                }

                @Override
                public void onConnectionSuspended(int i) {
                    //LOG
                }
            })
            .addApi(LocationServices.API)
            .build();
}
protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(30000);
    mLocationRequest.setFastestInterval(10000); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

private void Loc_Update() {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    Task<LocationSettingsResponse> task = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
    task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
        @Override
        public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
            try {
                LocationSettingsResponse response = task.getResult(ApiException.class);
                // All location settings are satisfied. The client can initialize location
                // requests here.
                if (ContextCompat.checkSelfPermission(MainMapActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

                    mFusedLocationClient.requestLocationUpdates(mLocationRequest,new LocationCallback(){
                                @Override
                                public void onLocationResult(LocationResult locationResult) {
                                    for (Location location : locationResult.getLocations()) {
                                        //Do what you want with location
                                        //like update camera
                                        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16f));
                                    }

                                }
                            },null);

                }
            } catch (ApiException exception) {
                switch (exception.getStatusCode()) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the
                        // user a dialog.
                        try {
                            // Cast to a resolvable exception.
                            ResolvableApiException resolvable = (ResolvableApiException) exception;
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            resolvable.startResolutionForResult(MainMapActivity.this, 2001);
                            break;
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        } catch (ClassCastException e) {
                            // Ignore, should be an impossible error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.

                        break;
                }
            }}
    });

}
查看更多
登录 后发表回答