gpt4 book ai didi

android - 如何在 Oreo 后台监控地理围栏?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:21 27 4
gpt4 key购买 nike

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

当应用程序处于后台时,如何获取地理围栏转换触发器?

我也尝试过使用 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")
}
}

list 中的接收器:

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

谢谢

编辑:IntentService 版本

待定意向:

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

Intent 服务:

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

list 中的服务:

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

最佳答案

当在后台达到地理围栏转换时,您应该每隔几分钟在 Android 8 上获得一个 Intent。

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

Handle geofence transitions When Location Services detects that the user has entered or exited a geofence, it sends out the Intent contained in the PendingIntent you included in the request to add geofences. This Intent is received by a service like GeofenceTransitionsIntentService, which obtains the geofencing event from the intent, determines the type of Geofence transition(s), and determines which of the defined geofences was triggered. It then sends a notification as the output.

Note: On Android 8.0 (API level 26) and higher, if an app is running in the background while monitoring a geofence, then the device responds to geofencing events every couple of minutes. To learn how to adapt your app to these response limits, see Background Location Limits.

一旦注册了地理围栏服务,它仍然存在,您无事可做,只需检查您的 IntentService 是否有特定的 PendingIntent,排除当设备重新启动时您需要重新注册您的地理围栏服务。

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

关于android - 如何在 Oreo 后台监控地理围栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50964988/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com