如何在奥利奥的后台监控地理围栏?



我遵循了本教程:https://developer.android.com/training/location/geofencing 并在Android <8上运行良好,但是在奥利奥,由于新的操作系统背景限制,我遇到了问题。

当应用在后台运行时,如何获取地理围栏过渡触发器?

我也尝试使用BroadcastReceiver而不是IntentService,但结果是一样的。

待处理的意图:

private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(context, GeofenceBroadcastReceiver::class.java)
intent.action = "com.example.GEOFENCE_TRANSITION"
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}

注册地理围栏:

geofencingClient.addGeofences(request, geofencePendingIntent).run {
addOnSuccessListener {
Log.d(TAG, "Geofence added")
}
addOnFailureListener {
Log.e(TAG, "Failed to create geofence")
}
} 

广播接收器:

class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
Log.d(TAG, "onReceive")
}
}

清单中的接收器:

<receiver android:name=".GeofenceBroadcastReceiver">
<intent-filter>
<action android:name="com.example.GEOFENCE_TRANSITION"/>
</intent-filter>
</receiver>

谢谢

编辑:意图服务版本

待处理的意图:

private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(context, GeofenceIntentService::class.java)
PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}

意向服务:

class GeofenceIntentService : IntentService("GeofenceIntentService") {
override fun onHandleIntent(p0: Intent?) {
Log.d(TAG, "onHandleIntent")
}
}

清单中的服务:

<service android:name=".GeofenceIntentService"/>

在后台到达地理围栏过渡时,您应该每隔几分钟在 Android 8 上获得一次意向。

请参阅:https://developer.android.com/training/location/geofencing#java

处理地理围栏过渡 当定位服务检测到用户已进入或退出地理围栏时,它会发出您在添加地理围栏的请求中包含的待处理意图中包含的意图。此意向由 GeofenceTransitionsIntentService 等服务接收,该服务从意向获取地理围栏事件,确定地理围栏转换的类型,并确定触发了哪些定义的地理围栏。然后,它会发送通知作为输出。

注意:在 Android 8.0(API 级别 26(及更高版本中,如果应用在监控地理围栏时在后台运行,则设备每隔几分钟就会响应一次地理围栏事件。若要了解如何使应用适应这些响应限制,请参阅后台位置限制。

注册地理围栏服务后,它仍然存在,你无事可做,只需检查您的 IntentService 以了解特定的待处理意图,排除在重新启动设备时需要重新注册地理围栏服务。

还要检查:https://developer.android.com/about/versions/oreo/background-location-limits

>我使用 dexter 库获得权限地理围栏,这项工作适用于 Android 8 9 10 及更高版本,您必须添加后台权限

Dexter.withActivity(this@Activity_Map)
.withPermissions(
Manifest.permission.ACCESS_COARSE_LOCATION
,Manifest.permission.ACCESS_FINE_LOCATION
,Manifest.permission.ACCESS_BACKGROUND_LOCATION
)
.withListener(object: MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
report?.let {
if(report.areAllPermissionsGranted()){
//put your code here
}
}