Fused Location Api устарел [дубликат]

Я согласен с ответом от zacherates.

Но вы можете сделать вызов intern () в ваших нелиберальных строках.

Из примера zacherates:

// ... but they are not the same object
new String("test") == "test" ==> false 

Если вы ставите нелитеральное равенство строки, это правда

new String("test").intern() == "test" ==> true 
46
задан vvvv 29 September 2017 в 04:42
поделиться

8 ответов

проблема с вашим оператором import

удаляет это

import android.location.LocationListener;

add

import com.google.android.gms.location.LocationListener;
81
ответ дан Somesh Kumar 16 August 2018 в 08:03
поделиться
  • 1
    Спасибо, что это работает сейчас :) – vvvv 29 September 2017 в 05:10
  • 2
    lol смотрел вокруг, не знаю, как отметить как ответ XD – vvvv 29 September 2017 в 05:22
  • 3
    @vvvv Разве вы не отмечаете это как ответ? потому что я уверен, что многие столкнутся с этой проблемой в ближайшем будущем, и ваш вопрос и этот ответ помогут им найти правильное решение. – Somesh Kumar 29 September 2017 в 05:22
  • 4
    Мне нравится, как Google docs все еще говорят вам использовать старый API: developer.android.com/training/location/… – mxcl 20 October 2017 в 01:22
  • 5
    @Fraid Да, предупреждение ушло .. и ссылка, которую вы указали, также гласит, что новая версия служб google play не будет терпеть крах, если пользователь обновит приложение. Думаю, я должен сейчас обновить свой ответ. – Somesh Kumar 14 November 2017 в 06:13

Последнее обновление (21 ноября 2017 года):

Предупреждение исчезло. Службы Google Play 11.6 6 ноября 2017 года, примечание к выпуску говорит: Я думаю, что Play Services не будет разбиваться, когда он обновится в фоновом режиме. Итак, теперь мы можем использовать новый FusedLocationProviderClient.


Важное обновление (24 октября 2017 года):

Вчера Google обновил официальную страницу разработчика с предупреждением , в котором говорится, что

< blockquote>

Пожалуйста, продолжайте использовать класс FusedLocationProviderApi и не переноситесь в класс FusedLocationProviderClient до тех пор, пока не будут доступны сервисы Google Play версии 12.0.0, которые, как ожидается, будут отправлены в начале 2018 года. Использование FusedLocationProviderClient до версии 12.0.0 вызывает клиентское приложение для сбоя при обновлении сервисов Google Play на устройстве. Приносим извинения за возможные неудобства.

Поэтому я думаю, что мы должны продолжать использовать устаревшие LocationServices.FusedLocationApi, пока Google не решит проблему.


Оригинальный ответ

Это происходит, потому что FusedLocationProviderApi устарел в последней версии сервисов Google Play. Вы можете проверить здесь . В официальном руководстве предлагается использовать FusedLocationProviderClient . Вы можете найти подробное руководство здесь .

, например, внутри onCreate() создать экземпляр FusedLocationProviderClient

 mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

и запросить последнюю известную местоположение все, что вам нужно сделать, это позвонить

mFusedLocationClient.getLastLocation()
    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            // Got last known location. In some rare situations, this can be null.
            if (location != null) {
                // Logic to handle location object
            }
        }
    });

Простой не так ли?

81
ответ дан Somesh Kumar 16 August 2018 в 09:56
поделиться
  • 1
    Спасибо, что это работает сейчас :) – vvvv 29 September 2017 в 05:10
  • 2
    lol смотрел вокруг, не знаю, как отметить как ответ XD – vvvv 29 September 2017 в 05:22
  • 3
    @vvvv Разве вы не отмечаете это как ответ? потому что я уверен, что многие столкнутся с этой проблемой в ближайшем будущем, и ваш вопрос и этот ответ помогут им найти правильное решение. – Somesh Kumar 29 September 2017 в 05:22
  • 4
    Мне нравится, как Google docs все еще говорят вам использовать старый API: developer.android.com/training/location/… – mxcl 20 October 2017 в 01:22
  • 5
    @Fraid Да, предупреждение ушло .. и ссылка, которую вы указали, также гласит, что новая версия служб google play не будет терпеть крах, если пользователь обновит приложение. Думаю, я должен сейчас обновить свой ответ. – Somesh Kumar 14 November 2017 в 06:13

Для здравомыслия я придерживаюсь 11.2.0. Я не понимаю усталости. По состоянию на ноябрь / 03/2017 документация Google до сих пор ссылается на: LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mListener);

0
ответ дан Juan Mendez 16 August 2018 в 08:03
поделиться

Да, это устарело! Вот некоторые моменты, которые вам понадобятся при использовании нового FusedLocationProviderClient .

  1. импортировать его как import com.google.android.gms.location.FusedLocationProviderClient;
0
ответ дан Malith 16 August 2018 в 08:03
поделиться
   // Better to use GoogleApiClient to show device location. I am using this way in my aap.

    public class SuccessFragment extends Fragment{
        private TextView txtLatitude, txtLongitude, txtAddress;
        // private AddressResultReceiver mResultReceiver;
        // removed here because cause wrong code when implemented and
        // its not necessary like the author says

        //Define fields for Google API Client
        private FusedLocationProviderClient mFusedLocationClient;
        private Location lastLocation;
        private LocationRequest locationRequest;
        private LocationCallback mLocationCallback;

        private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 14;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_location, container, false);

            txtLatitude = (TextView) view.findViewById(R.id.txtLatitude);
            txtLongitude = (TextView) view.findViewById(R.id.txtLongitude);
            txtAddress = (TextView) view.findViewById(R.id.txtAddress);

            // mResultReceiver = new AddressResultReceiver(null);
            // cemented as above explained
            try {
                mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
                mFusedLocationClient.getLastLocation()
                        .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                            @Override
                            public void onSuccess(Location location) {
                                // Got last known location. In some rare situations this can be null.
                                if (location != null) {
                                    // Logic to handle location object
                                    txtLatitude.setText(String.valueOf(location.getLatitude()));
                                    txtLongitude.setText(String.valueOf(location.getLongitude()));
                                    if (mResultReceiver != null)
                                        txtAddress.setText(mResultReceiver.getAddress());
                                }
                            }
                        });
                locationRequest = LocationRequest.create();
                locationRequest.setInterval(5000);
                locationRequest.setFastestInterval(1000);
                if (txtAddress.getText().toString().equals(""))
                    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                else
                    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

                mLocationCallback = new LocationCallback() {
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        for (Location location : locationResult.getLocations()) {
                            // Update UI with location data
                            txtLatitude.setText(String.valueOf(location.getLatitude()));
                            txtLongitude.setText(String.valueOf(location.getLongitude()));
                        }
                    }

                    ;
                };
            } catch (SecurityException ex) {
                ex.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return view;
        }

        @Override
        public void onStart() {
            super.onStart();

            if (!checkPermissions()) {
                startLocationUpdates();
                requestPermissions();
            } else {
                getLastLocation();
                startLocationUpdates();
            }
        }

        @Override
        public void onPause() {
            stopLocationUpdates();
            super.onPause();
        }

        /**
         * Return the current state of the permissions needed.
         */
        private boolean checkPermissions() {
            int permissionState = ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_COARSE_LOCATION);
            return permissionState == PackageManager.PERMISSION_GRANTED;
        }

        private void startLocationPermissionRequest() {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_PERMISSIONS_REQUEST_CODE);
        }


        private void requestPermissions() {
            boolean shouldProvideRationale =
                    ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                            Manifest.permission.ACCESS_COARSE_LOCATION);

            // Provide an additional rationale to the user. This would happen if the user denied the
            // request previously, but didn't check the "Don't ask again" checkbox.
            if (shouldProvideRationale) {
                Log.i(TAG, "Displaying permission rationale to provide additional context.");

                showSnackbar(R.string.permission_rationale, android.R.string.ok,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                // Request permission
                                startLocationPermissionRequest();
                            }
                        });

            } else {
                Log.i(TAG, "Requesting permission");
                // Request permission. It's possible this can be auto answered if device policy
                // sets the permission in a given state or the user denied the permission
                // previously and checked "Never ask again".
                startLocationPermissionRequest();
            }
        }

        /**
         * Callback received when a permissions request has been completed.
         */
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                               @NonNull int[] grantResults) {
            Log.i(TAG, "onRequestPermissionResult");
            if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
                if (grantResults.length <= 0) {
                    // If user interaction was interrupted, the permission request is cancelled and you
                    // receive empty arrays.
                    Log.i(TAG, "User interaction was cancelled.");
                } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission granted.
                    getLastLocation();
                } else {
                    // Permission denied.

                    // Notify the user via a SnackBar that they have rejected a core permission for the
                    // app, which makes the Activity useless. In a real app, core permissions would
                    // typically be best requested during a welcome-screen flow.

                    // Additionally, it is important to remember that a permission might have been
                    // rejected without asking the user for permission (device policy or "Never ask
                    // again" prompts). Therefore, a user interface affordance is typically implemented
                    // when permissions are denied. Otherwise, your app could appear unresponsive to
                    // touches or interactions which have required permissions.
                    showSnackbar(R.string.permission_denied_explanation, R.string.settings,
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    // Build intent that displays the App settings screen.
                                    Intent intent = new Intent();
                                    intent.setAction(
                                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package",
                                            BuildConfig.APPLICATION_ID, null);
                                    intent.setData(uri);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                }
                            });
                }
            }
        }


        /**
         * Provides a simple way of getting a device's location and is well suited for
         * applications that do not require a fine-grained location and that do not need location
         * updates. Gets the best and most recent location currently available, which may be null
         * in rare cases when a location is not available.
         * <p>
         * Note: this method should be called after location permission has been granted.
         */
        @SuppressWarnings("MissingPermission")
        private void getLastLocation() {
            mFusedLocationClient.getLastLocation()
                    .addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            if (task.isSuccessful() && task.getResult() != null) {
                                lastLocation = task.getResult();

                                txtLatitude.setText(String.valueOf(lastLocation.getLatitude()));
                                txtLongitude.setText(String.valueOf(lastLocation.getLongitude()));

                            } else {
                                Log.w(TAG, "getLastLocation:exception", task.getException());
                                showSnackbar(getString(R.string.no_location_detected));
                            }
                        }
                    });
        }

        private void stopLocationUpdates() {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        }

        private void startLocationUpdates() {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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;
            }
            mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, null);
        }

        // private void showSnackbar(final String text) {
        //    if (canvasLayout != null) {
        //        Snackbar.make(canvasLayout, text, Snackbar.LENGTH_LONG).show();
        //    }
        //}
        // this also cause wrong code and as I see it dont is necessary
        // because the same method which is really used


        private void showSnackbar(final int mainTextStringId, final int actionStringId,
                                  View.OnClickListener listener) {
            Snackbar.make(getActivity().findViewById(android.R.id.content),
                    getString(mainTextStringId),
                    Snackbar.LENGTH_INDEFINITE)
                    .setAction(getString(actionStringId), listener).show();
        }
    }

И наш фрагмент _location.xml

       <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout 
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/locationLayout"
            android:layout_below="@+id/txtAddress"
            android:layout_width="match_parent"
            android:layout_height="@dimen/activity_margin_30dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/txtLatitude"
                android:layout_width="@dimen/activity_margin_0dp"
                android:layout_height="@dimen/activity_margin_30dp"
                android:layout_weight="0.5"
                android:gravity="center"
                android:hint="@string/latitude"
                android:textAllCaps="false"
                android:textColorHint="@color/colorPrimaryDark"
                android:textColor="@color/colorPrimaryDark" />

            <TextView
                android:id="@+id/txtLongitude"
                android:layout_width="@dimen/activity_margin_0dp"
                android:layout_height="@dimen/activity_margin_30dp"
                android:layout_weight="0.5"
                android:gravity="center"
                android:hint="@string/longitude"
                android:textAllCaps="false"
                android:textColorHint="@color/colorPrimary"
                android:textColor="@color/colorPrimary" />
        </LinearLayout>
5
ответ дан Ruan_Lopes 16 August 2018 в 08:03
поделиться
  • 1
    Не удается разрешить символ AddressResultReceiver – V.Y. 15 May 2018 в 07:51
  • 2
    удалите эту строку. Остальная часть кода будет работать для вас – JoboFive 15 May 2018 в 13:19
  • 3
    все еще не работает – V.Y. 15 May 2018 в 13:31
  • 4
    Какая проблема возникает при использовании кода. Поделитесь своей ошибкой. – JoboFive 15 May 2018 в 23:58
  • 5
    не удалось получить местоположение в следующий интервал – V.Y. 17 May 2018 в 06:13
-1
ответ дан Karim Elbahi 6 September 2018 в 04:33
поделиться
1
ответ дан Ketan Ramani 29 October 2018 в 11:10
поделиться
0
ответ дан Rasoul Miri 29 October 2018 в 11:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: