首页 > 解决方案 > 如何删除所有活动的地理围栏?

问题描述

在开发过程中,我一直在使用地理围栏进行测试,最初添加了许多必须.setExpirationDuration()无限期的地理围栏(NEVER_EXPIRE)。他们在我的广播接收器中执行了一些代码,但我从未删除实际的地理围栏,而且我没有他们的requestid.

如何检查这些地理围栏是否仍处于活动状态?我想摆脱它们以防止它们在内存中堆积。

代码与Android官方教程基本一致:创建和监控Geofences

代码:

private fun createOnlineGeofence(currentLocation: GeoPoint){
    val geofenceId = randomAlphanumeric(10, 12)
    with(sharedPref.edit()) {
        putString("geofenceId", geofenceId)
        apply()
    }
    user.geofence = Geofence.Builder().apply {
        setRequestId(randomAlphanumeric(10, 12))
            setCircularRegion(currentLocation.latitude, currentLocation.longitude, 400f)
            setExpirationDuration(28800000)
            setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT or Geofence.GEOFENCE_TRANSITION_ENTER)
            setNotificationResponsiveness(300000)
    }.build()
    val geofenceRequest = GeofencingRequest.Builder().apply {
        setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
        addGeofence(user.geofence)
    }.build()
    val onlineGeofencePendingIntent: PendingIntent by lazy {
        val intent = Intent(mContext.applicationContext, GeofenceBroadcastReceiver::class.java)
        intent.putExtra("geofenceId", geofenceId)
        PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    }
    Log.d(TAG, "Created online Geofence, geofenceId: ${user.geofence?.requestId}")
    if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        geofencingClient.addGeofences(geofenceRequest, onlineGeofencePendingIntent)?.run {
            addOnSuccessListener {
                Toast.makeText(mContext, "Online Geofence added", Toast.LENGTH_LONG).show()
                Log.d(TAG, "Online geofence added")
            }
            addOnFailureListener {
                exception -> Log.d(TAG, "Exception: $exception")
            }
        }
    }
}

标签: androidandroid-geofence

解决方案


你不能。Google 没有提供 API 来检查哪些地理围栏处于活动状态。您所能做的就是在您身边保留一个活动地理围栏列表(sqlite 或其他),并在需要时停用它们。


推荐阅读