【发布时间】: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