【问题标题】:Android LocationServices.FusedLocationApi deprecatedAndroid LocationServices.FusedLocationApi 已弃用
【发布时间】:2018-03-10 22:38:52
【问题描述】:

我不明白为什么 LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, this);"FusedLocationApi" 被划掉并指出它说已弃用。 Click here to view Image

import android.location.Location;
import android.location.LocationListener;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MaintainerMapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocaton;
LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maintainer_map2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}


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

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onConnected(@Nullable Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

【问题讨论】:

  • 如果它被弃用了,请检查我正在使用这个 LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, this);
  • @OmarHayat FusedLocationApi 已删除
  • 检查你的依赖项我使用这个 compile 'com.google.android.gms:play-services-location:9.4.0'
  • 你在 oncreate 方法中使用这个 mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build();
  • @OmarHayat 我正在使用 compile 'com.google.android.gms:play-services-location:11.4.0' 并且在我更改为 9.4.0 后它解决了问题,为什么它会解决换号码后?

标签: java android deprecated android-fusedlocation


【解决方案1】:

原答案

发生这种情况是因为 FusedLocationProviderApi 在最新版本的 google play 服务中已弃用。你可以检查它here。官方指南现在建议使用FusedLocationProviderClient。您可以找到详细指南here

例如在 onCreate()onViewCreated() 内部创建一个 FusedLocationProviderClient 实例

科特林

val fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext())

而要请求最后一个已知位置,您只需拨打电话

fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
            location?.let { it: Location ->
                // Logic to handle location object
            } ?: kotlin.run {
                // Handle Null case or Request periodic location update https://developer.android.com/training/location/receive-location-updates
            }
        }

Java

FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext());

fusedLocationClient.getLastLocation().addOnSuccessListener(requireActivity(), location -> {
        if (location != null) {
            // Logic to handle location object
        } else {
            // Handle null case or Request periodic location update https://developer.android.com/training/location/receive-location-updates
        }
    });

很简单,不是吗?


重要更新(2017 年 10 月 24 日):

昨天谷歌更新了其官方开发者页面,上面写着a warning

请继续使用 FusedLocationProviderApi 类,并且在 Google Play 服务版本 12.0.0 可用之前不要迁移到 FusedLocationProviderClient 类,该版本预计将于 2018 年初发布。使用版本 12.0.0 之前的 FusedLocationProviderClient 会导致客户端应用在设备上更新 Google Play 服务时崩溃。对于由此可能造成的任何不便,我们深表歉意。

所以我认为我们应该继续使用已弃用的LocationServices.FusedLocationApi,直到 Google 解决了这个问题。


最新更新(2017 年 11 月 21 日):

警告现在消失了。 Google Play services 11.6 November 6, 2017, release note 说: 我认为 Play Services 在后台自行更新时不会崩溃。所以我们现在可以使用新的FusedLocationProviderClient

【讨论】:

  • 我喜欢 Google 文档仍然告诉您使用旧 API:developer.android.com/training/location/…
  • getLastLocation() 是在做什么 LocationServices.FusedLocationApi.requestLocationUpdates() 吗?到目前为止,如此奇怪的是文档仍然指向这种旧方式。这很令人困惑。 developer.android.com/training/location/…
  • @JuanMendez 我同意。他们需要努力维护适当的最新示例。顺便说一句getLastLocation() 只返回设备的最新已知位置。您可以使用新的requestLocationUpdates(LocationRequest request, PendingIntent callbackIntent) 方法请求位置更新。
  • @Fraid 是的,警告消失了。您提供的链接还指出,如果用户更新应用程序,新版本的 google play 服务不会崩溃。我想我现在应该更新我的答案。
  • 还有什么简单的?您的示例没有requestLocationUpdatesmFusedLocationClient.getLastLocation() 有什么困难?你最好举个例子requestLocationUpdates
【解决方案2】:
   // 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();
        }
    }

还有我们的 fragment_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>

【讨论】:

  • 删除此行。其余代码将为您工作
  • 无法在下一个间隔获取位置
  • @Vishal 我在您需要检查清单和内部代码中的位置权限的每个实例中获取实时位置
  • 感谢您的代码。但是我有一个问题,如果我每 100 米后需要定位并将其发送到服务器,我该怎么办?请帮忙。
  • 这样使用:locationRequest =LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(90000) .setSmallestDisplacement(10) .setFastestInterval(10000);
【解决方案3】:

使用这个方法

mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());

In Detail Refer My This Answer

【讨论】:

    【解决方案4】:

    是的,它已被弃用!
    以下是您在使用新的FusedLocationProviderClient 时需要注意的几点。

    1. 将其导入为 import com.google.android.gms.location.FusedLocationProviderClient; ?
    2. 我注意到您正在实现LocationListener 接口。在 mFusedLocationClient.requestLocationUpdates() 方法中,现在它不需要 LocationListener 作为参数。您可以提供LocationCallback。因为这是一个抽象类,你不能像 LocationListener 那样实现它。制作一个回调方法并传递它而不是 Google 的 guide 中提到的“this”。将其导入为import com.google.android.gms.location.LocationCallback;
    3. 使用 LocationCallback,您将拥有 onLocationResult() 而不是 onLocationChanged()。它返回 LocationResult 对象而不是 Location 对象。使用 LocationResult.getLastLocation() 获取此结果对象中可用的最新位置。导入为import com.google.android.gms.location.LocationResult;

    【讨论】:

      【解决方案5】:

      是的,它已被弃用。 FusedLocationProviderClientFusedLocationProviderApi 容易,因为FusedLocationProviderApi 通常也需要GoogleApiClient,我们需要手动连接到Google Play Service。如果您之前使用过GoogleApiClient,现在不再需要GoogleApiClient (more here)。

      要获取最后的位置,可以使用这个函数:

      import com.google.android.gms.location.FusedLocationProviderClient;
      import com.google.android.gms.tasks.OnCompleteListener;
      
      public class MainActivity extends AppCompatActivity{
      //before public class MainActivity extends AppCompatActivity implements LocationListener,...,...
      
      
      private static final String TAG = "MainActivity";
      public static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 101;
      private FusedLocationProviderClient mFusedLocationClient;
      private Location mGetedLocation;
      
      private double currentLat, currentLng;
      
      private void getLastLocation() {
          if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                  requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_FINE_LOCATION);
              }
              return;
          }
          mFusedLocationClient.getLastLocation()
                  .addOnCompleteListener(this, new OnCompleteListener<Location>() {
                      @Override
                      public void onComplete(@NonNull Task<Location> task) {
                          if (task.isSuccessful() && task.getResult() != null) {
                              mGetedLocation = task.getResult();
                              currentLat = mGetedLocation.getLatitude();
                              currentLng = mGetedLocation.getLongitude();
                              //updateUI();
                          }else{
                              Log.e(TAG, "no location detected");
                              Log.w(TAG, "getLastLocation:exception", task.getException());
                          }
                      }
                  });
      
      }
      

      【讨论】:

        【解决方案6】:

        使用 getFusedLocationProviderClient 代替 LocationServices.FusedLocationApi。

        科特林

        activity?.let { activity ->
              val client = LocationServices.getFusedLocationProviderClient(activity)
                   client.lastLocation.addOnCompleteListener(activity, OnCompleteListener<Location> {
                      // it.result.latitude
                      // it.result.longitude
              })
        }
        

        java

        FusedLocationProviderClient client =
                LocationServices.getFusedLocationProviderClient(this);
        
        // Get the last known location
        client.getLastLocation()
                .addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        // ...
                    }
                });
        

        【讨论】:

          【解决方案7】:

          问题在于您的导入语句

          删除这个

          import android.location.LocationListener;
          

          添加

          import com.google.android.gms.location.LocationListener;
          

          【讨论】:

            猜你喜欢
            • 2012-12-25
            • 2021-08-31
            • 2015-09-18
            • 2018-02-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多