我试图在 Android 上使用 Google Geofencing API 设置地理围栏。我创建了一个 BroadcastReceiver 来处理转换事件,并使用显式意图创建了一个待处理的意图,我在创建地理围栏时将其传递给 API。但是,onReceive我的接收器永远不会被调用。我尝试过使用不同的设置setNotificationResponsiveness和setInitialTrigger但没有任何帮助。我已经在物理设备(带有 Android 10 的诺基亚 7.1)和带有 Android 10 和 6 的两个模拟器上尝试过它,但它在任何一个设备上都不起作用。我尝试等待几分钟以触发事件,但它永远不会触发。我也尝试了不同的半径值,没有结果。在 Android 10 上,我可以在系统进程日志中看到地理围栏确实已注册,但随后我只能看到一些关于位置可用性的条目,例如这个。即使isLocationAvailable是真的(我不知道这取决于什么),接收器仍然不会被触发:
I/GeofencerStateMachine: sendNewLocationAvailability: availability=LocationAvailability[isLocationAvailable: false]
这是一个不起作用的最小代码示例:
GeofenceReceiver.kt
class GeofenceReceiver : BroadcastReceiver() {
companion object {
fun makePendingIntent(context: Context) = PendingIntent.getBroadcast(
context,
1239,
Intent(context, GeofenceReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
}
override fun onReceive(context: Context, intent: Intent) {
Log.e("geofencereceiver", "received event")
// some code
}
}
AndroidManifest.xml(不相关部分省略)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.patlejch.geofenceminimal">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<application ...>
....
<receiver android:name=".GeofenceReceiver" />
<!-- note that setting the receiver as exported makes no difference (and it shouldn't) -->
</application>
</manifest>
注册地理围栏(this作为一个活动)。当此代码被执行时,应用程序已经拥有ACCESS_FINE_LOCATION并ACCESS_BACKGROUND_LOCATION授予:
// googleplex mountain view
val latitude = 37.421912
val longitude = -122.084068
val radius = 250.0f
val geofenceGms = Geofence.Builder()
.setRequestId("test_geofence")
.setCircularRegion(latitude, longitude, radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
//.setNotificationResponsiveness(...)
.build()
val request = GeofencingRequest.Builder()
//.setInitialTrigger(Geofence.GEOFENCE_TRANSITION_EXIT)
.addGeofence(geofenceGms)
.build()
val geofencingClient = LocationServices.getGeofencingClient(this)
try {
geofencingClient.addGeofences(request, GeofenceReceiver.makePendingIntent(this))
.addOnSuccessListener {
Toast.makeText(this, "registered", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Toast.makeText(this, "failure", Toast.LENGTH_SHORT).show()
}
} catch (e: SecurityException) {}
有没有人遇到过他们成功解决的类似问题?