gpt4 book ai didi

android - 如何在 Activity 中收听 Geofence BroadcastReceiver?

转载 作者:行者123 更新时间:2023-11-29 02:19:18 24 4
gpt4 key购买 nike

我关注了Android's tutorial on adding a Geofence with a BroadcastReceiver .

这成功地向我发送了有关地理围栏转换的通知。

但是,我现在还需要在我的 fragment/Activity 中接收广播,以便我可以执行一些 UI 更改。

下面是我当前注册地理围栏广播的代码:

MapFragment.kt

private fun createOnlineGeofence(currentLocation: GeoPoint){
val geofenceId = "ONLINE_GEOFENCE_ID"
with(sharedPref.edit()) {
putString("geofenceId", geofenceId)
apply()
}
/** Create Geofence */
user.geofence = Geofence.Builder().apply {
setRequestId(geofenceId)
setCircularRegion(currentLocation.latitude, currentLocation.longitude, 400f)
setExpirationDuration(Geofence.NEVER_EXPIRE)
setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT)
setNotificationResponsiveness(300000)
}.build()
val geofenceRequest = GeofencingRequest.Builder().apply {
addGeofence(user.geofence)
}.build()
val pendingIntent: PendingIntent by lazy {
val intent = Intent(mContext.applicationContext, GeofenceBroadcastReceiverTesting::class.java)
intent.putExtra("type", "online")
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, pendingIntent)?.run {
addOnSuccessListener {
Log.d(TAG, "Online geofence added")
}
addOnFailureListener {
exception -> Log.d(TAG, "Exception: $exception")
}
}
}
}

如何在我的 Fragment/Activity 中监听 Geofence 转换?

最佳答案

你可以看看这个 solution here使用 LocalBroadcastManager (LBM)。这个想法是告诉 LBM 你想听到某个 IntentFilter 的广播 & 在 Geofence BroadcastReceiver 中,你可以调用 LBM 发送广播以供 Activity 接收。不用说,您必须在 Activity 本身中实现 ​​BroadcastReceiver 才能接受本地广播。

关于android - 如何在 Activity 中收听 Geofence BroadcastReceiver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57438810/

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