【发布时间】:2020-05-03 13:23:44
【问题描述】:
我正在制作一个笔记应用程序,当我只在地理围栏触发器上输入时,如果我在同一位置制作超过 1 条笔记并且只显示 1 条通知,则该应用程序会在您输入地理围栏时触发通知。
代码如下: 广播接收器
class GeofenceBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
//if (intent.action == ACTION_GEOFENCE_EVENT) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
val errorMessage = errorMessage(context, geofencingEvent.errorCode)
Log.e(TAG, errorMessage)
return
}
if (geofencingEvent.geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
Log.v(TAG, "context.getString(R.string.geofence_entered)")
val fenceId = when {
geofencingEvent.triggeringGeofences.isNotEmpty() ->
geofencingEvent.triggeringGeofences
else -> {
Log.e(TAG, "No Geofence Trigger Found! Abort mission!")
return
}
}
/*val foundIndex = GeofencingConstants.LANDMARK_DATA.indexOfFirst {
it.id == fenceId
}*/
// Unknown Geofences aren't helpful to us
/*if ( -1 == foundIndex ) {
Log.e(TAG, "Unknown Geofence: Abort Mission")
return
}*/
for (geofence in fenceId){
sendGeofenceEnteredNotification(
context, geofence.requestId, intent.getStringExtra("note")!!
)
}
}
}
// }
}
------------- 添加地理围栏的方法 ---------------------------
private fun createPendingIntent(context: Context, note: Note) : PendingIntent{
val intent = Intent(context, GeofenceBroadcastReceiver::class.java)
intent.action = "MainActivity.treasureHunt.action.ACTION_GEOFENCE_EVENT"
intent.putExtra("note", note.note)
return PendingIntent.getBroadcast(context, note.date.toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun addGeofenceForNote(note: Note, context: Context) {
val geofencingClient = LocationServices.getGeofencingClient(context)
val geofence = Geofence.Builder()
.setRequestId(note.id)
.setCircularRegion(note.latitude, note.longitude, GeofencingConstants.GEOFENCE_RADIUS_IN_METERS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build()
// Build the geofence request
val geofencingRequest = GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofence(geofence)
.build()
geofencingClient.addGeofences(geofencingRequest, createPendingIntent(context, note))?.run {
addOnSuccessListener {
Log.e("Add Geofence", geofence.requestId)
}
addOnFailureListener {
if ((it.message != null)) {
Log.w("TAG", it.message!!)
}
}
}
}
我在同一位置做了 3 个笔记,第二个是触发广播接收器的那个。
附:即使地理围栏位于完全不同的位置,我仍然只能收到 1 条通知。据我所知,所有待处理的意图和通知都有不同的 ID。
提前打个招呼
【问题讨论】:
标签: android kotlin notifications geofencing android-geofence