BroadcastReceiver中的领域事务不起作用

时间:2018-09-03 18:59:58

标签: android broadcastreceiver realm android-broadcastreceiver

我向用户显示了带有操作的通知,我使用BroadcastReceiver处理了这些操作,从那里我更新了一个领域数据库,但是即使我确定(通过日志)交易得到了更新,它也没有更新。被执行。

NotificationBroadcastReceiver:

Promise

NoticeRealm:

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)

}

修改: 我只是让接收者开始一个空的活动(没有布局)来处理数据库。同样的事情发生了。我认为这不再是BroadcastReceiver问题。奇怪的是,其他领域的交易在其他活动/片段中运行得很好。

1 个答案:

答案 0 :(得分:0)

原来这不是领域的问题,这是我触发广播的方式,我是这样做的:

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会完全不同(但不是随机的,我每次都会看到相同的错误ID)。