“不推荐使用地理围栏API”

cap*_*abe 3 android android-geofence

我应该用什么代替它?此外,我针对此地理围栏应用程序的目标是 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Sim*_*onH 5

您使用的 Android 版本与不推荐使用的GeofencingApi. 的GeofencingApi是谷歌Play服务的一部分,并在发行11.0过时。

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

因此,您不再需要设置 aGoogleApiClient来访问地理围栏 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;
                        }
                    });
Run Code Online (Sandbox Code Playgroud)

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

有关更完整的解释,请参见此处此处

  • 我使用 geoFencingClient 已经有一段时间了。谷歌的例子没有费心展示在 onFailure() 中做什么 - 但我从实践经验中知道它有时无法添加地理围栏。为什么?我知道限制是 100,但即使在第二次添加时它也可能失败。为什么 ? (2认同)