【问题标题】:How to listen to a Geofence BroadcastReceiver in an Activity?如何在活动中收听地理围栏广播接收器?
【发布时间】:2019-09-23 20:21:19
【问题描述】:

我关注了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 转换?

【问题讨论】:

  • 您可以通过在onStart()(或onCreate())中调用registerReceiver(/*yourReceiverInstance*/)onStop()中的unregisterReceiver(/*yourReceiverInstance*/)(或onDestroy())。检查developer.android.com/guide/components/…

标签: android kotlin broadcastreceiver


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多