BroadcastReceiver中的域事务处理不起作用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BroadcastReceiver中的域事务处理不起作用相关的知识,希望对你有一定的参考价值。

我向用户显示了一个带有操作的通知,我使用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问题。奇怪的是,其他领域的交易在其他活动/片段中完美运行。

答案

事实证明这不是领域的问题,我是如何解雇广播的,我是这样做的:

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)没有这个标志。

以上是关于BroadcastReceiver中的域事务处理不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何修复 mandrill / mailchimp 事务性电子邮件问题收件人域不匹配

MainActivity中的BroadcastReceiver不接收广播意图

Oreo BroadcastReceiver短信收到不起作用

android 自定义视图中能不能定义BroadcastReceiver

BroadcastReceiver

处理:新建信任不能继续,因为联系不上指定的域