Подтвердить что ты не робот

LocationServices.SettingsApi устарела

Мой код:

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);

    }

но, к сожалению, LocationServices.SettingsApi устарела. Как заменить устаревший код на новый?

Я нашел чтение документов, что решение может состоять в использовании SettingsClient, но не может понять, как это сделать.

Любой идее, что делать, может обновить мой код?

4b9b3361

Ответ 1

LocationServices.SettingsApi устарела

Да, LocationServices.SettingsApi устарела

Как я могу заменить устаревший код новым?

Вам нужно использовать GoogleApi на основе API SettingsClient

ОТ ДОКУМЕНТОВ

SettingsClient

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

Основная точка входа для взаимодействия с API-интерфейсами настройки местоположения.

Этот API-интерфейс позволяет приложению легко убедиться, что системные параметры устройства правильно настроены для нужд приложения.

При выполнении запроса к службам определения местоположения системные настройки устройства могут находиться в состоянии, которое не позволяет приложению получать данные о местоположении, в которых оно нуждается. Например, сканирование GPS или Wi-Fi может быть отключено. Это намерение позволяет легко:

  • Определите, включены ли соответствующие системные настройки на устройстве для выполнения требуемого запроса местоположения.

  • По желанию, откройте диалоговое окно, которое позволяет пользователю включить необходимые настройки местоположения одним нажатием.

Я нашел в документах для чтения, что решением может быть использование SettingsClient, но не мог понять, как это сделать.

Следуйте этим шагам

Чтобы использовать этот API, сначала создайте LocationSettingsRequest.Builder и добавьте все запросы LocationRequest, которые будет использовать приложение:

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

Затем проверьте, удовлетворены ли текущие настройки местоположения:

Task<LocationSettingsResponse> result =
         LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());

Ответ 2

Я использую этот код после устаревания LocationServices.SettingsApi и FusedLocationApi

Этот код обеспечивает:

1) Запросить последнее местоположение

2) Периодическое обновление местоположения с помощью FusedLocationProviderClient

Все коды в вашей активности

//create this at top of onCreate 
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;
                }
            }}
    });

}

Ответ 3

новый код

 protected void createLocationRequest() {
    LocationRequest mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    SettingsClient client = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            Toast.makeText(MapActivity.this, "addOnSuccessListener", Toast.LENGTH_SHORT).show();
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
        }
    });

    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(MapActivity.this, "addOnFailureListener", Toast.LENGTH_SHORT).show();
            if (e instanceof ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MapActivity.this,
                            REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                }
            }
        }
    });
}