首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BroadcastReceiver中的领域事务不起作用

BroadcastReceiver中的领域事务不起作用
EN

Stack Overflow用户
提问于 2018-09-03 18:59:58
回答 1查看 234关注 0票数 0

我向用户展示了一个带有操作的通知,我用一个BroadcastReceiver处理这些操作,然后我更新了一个领域数据库,但是它没有被更新,尽管我确信(通过日志)事务会被执行。

NotificationBroadcastReceiver:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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的问题了。奇怪的是,其他领域事务在其他活动/片段中运行得非常完美。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-10 09:38:32

事实证明,这并不是领域的问题,而是我如何发射广播的,我是这样做的:

代码语言:javascript
复制
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,所以如下所示:

代码语言:javascript
复制
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 )。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52155055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档