我向用户展示了一个带有操作的通知,我用一个BroadcastReceiver处理这些操作,然后我更新了一个领域数据库,但是它没有被更新,尽管我确信(通过日志)事务会被执行。
NotificationBroadcastReceiver:
override fun onReceive(context: Context, intent: Intent) {
val notionId = intent.getStringExtra(NOTION_ID_EXTRA)
val actionType = intent.getIntExtra(ACTION_TYPE, ACTION_TYPE_PUTBACK)
when (actionType) {
ACTION_TYPE_PUTBACK -> {
Toast.makeText(context, R.string.notion_is_putback, Toast.LENGTH_SHORT).show()
}
ACTION_TYPE_ARCHIVE -> {
NotionsRealm.changeIdleState(notionId, true)
}
}
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(NotionsReminder.NOTION_NOTIFICATION_ID)
}NotionsRealm:
fun changeIdleState(id: String, state: Boolean) {
val realm = Realm.getDefaultInstance()
realm.executeTransaction {
val notion = it.where<Notion>().equalTo("id", id).findFirst()
notion?.isArchived = state
debug("${notion?.isArchived}") //prints true to the log, but the data doesn't change.
}
closeRealm(realm)
}
private fun closeRealm(realm: Realm) {
try {
realm.close()
} catch (e: Exception) {
error(e)
} finally {
debug("realm closed")
}
}编辑:我只是让接收方启动一个空活动(没有布局)来处理数据库。同样的事情也发生了。我认为这不再是BroadcastReceiver的问题了。奇怪的是,其他领域事务在其他活动/片段中运行得非常完美。
发布于 2018-09-10 09:38:32
事实证明,这并不是领域的问题,而是我如何发射广播的,我是这样做的:
fun notificationAction(context: Context, id: String, actionType: Int): PendingIntent {
return PendingIntent.getBroadcast(
context, actionType,
Intent(context, NotificationBroadcastReceiver::class.java).apply {
putExtra(NotificationBroadcastReceiver.NOTION_ID_EXTRA, id)
putExtra(NotificationBroadcastReceiver.ACTION_TYPE, actionType)
}, 0)
}我发现传递的id是不正确的,经过一些搜索后,我发现我应该在广播中包含这个标志:PendingIntent.FLAG_UPDATE_CURRENT,所以如下所示:
fun notificationAction(context: Context, id: String, actionType: Int): PendingIntent {
return PendingIntent.getBroadcast(
context, actionType,
Intent(context, NotificationBroadcastReceiver::class.java).apply {
putExtra(NotificationBroadcastReceiver.NOTION_ID_EXTRA, id)
putExtra(NotificationBroadcastReceiver.ACTION_TYPE, actionType)
}, PendingIntent.FLAG_UPDATE_CURRENT)
}现在传递的id是正确的,我仍然不明白为什么会发生这种情况,或者没有这个标志,为什么id完全不同(但不是随机的,我每次都看到相同的错误id )。
https://stackoverflow.com/questions/52155055
复制相似问题