【问题标题】:"GeofencingAPI is deprecated"“GeofencingAPI 已弃用”
【发布时间】:2018-02-08 13:34:49
【问题描述】:

我应该用什么替换它?另外,我针对这个地理围栏应用程序的目标是 Android 7.0。

private void addNewGeofence(GeofencingRequest request) {
    Log.i(TAG, "GEOFENCE: Adding new Geofence.");
    if (checkPermissions()){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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;
        }
        LocationServices.GeofencingApi.addGeofences(
                googleApiClient, request, createGeofencePendingIntent()).setResultCallback(this);
    }

}

【问题讨论】:

  • 使用GeofencingClient

标签: android android-geofence


【解决方案1】:

您使用的 Android 版本与已弃用的GeofencingApi 的使用无关。 GeofencingApi 是 Google Play 服务的一部分,在 11.0 版中已弃用。

此时,替代 GeofencingClient 已添加到 Google Play 服务中。

因此,您不再需要设置 GoogleApiClient 来访问地理围栏 API。只需设置一个地理围栏客户端,然后以与之前调用类似的方式调用它。主要区别在于您不必实现结果回调,您可以添加所需的任何成功/失败/完成回调。

所以对于您的代码,它将是......

client = LocationServices.getGeofencingClient;
...
client.addGeofences(request, createGeofencePendingIntent())
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            // your success code
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            // your fail code;
                        }
                    });

请注意,在调用此代码之前,您仍需要检查您的权限。

请参阅 herehere 以获得更完整的解释。

【讨论】:

  • 我使用 geoFencingClient 已经有一段时间了。谷歌示例并没有费心展示在 onFailure() 中要做什么——但我从实践经验中知道,它有时确实无法添加地理围栏。为什么?我知道限制是 100,但即使只是在第二次添加它也可能会失败。为什么?
猜你喜欢
  • 2014-02-12
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
相关资源
最近更新 更多