gpt4 book ai didi

android - Anko 的 uiThread 偶尔不会被触发

转载 作者:搜寻专家 更新时间:2023-11-01 07:44:51 26 4
gpt4 key购买 nike

我目前正在使用 Anko 的 doAsync 来处理异步任务。具体来说,我使用它来解析对数据对象的 ArrayList 的响应 json,如下所示:

// Asynchronously parse server response
doAsync {
val itemlist = parseResponse(response)
uiThread {
Otto.INSTANCE.post(UpdateRedeemedVoucherViewsEvent(itemlist))
}
}

大多数时候,就像在 Google Pixel (Android 8.0.0) 上一样,它工作得很好。我的对象得到解析,Otto 总线事件 将发布到 ui 线程

但在极少数情况下,此过程会失败。到目前为止,我注意到 ui 线程调用不会在 Galaxy S5 Mini (Android 5.1.1) 上触发。虽然我的数据解析没有任何错误或异常,但 uiThread 括号中的代码 fragment 不会被执行。

到目前为止,我无法确定此行为的任何原因。没有 logcat 日志,什么都没有。没有关于何时会出现此错误的方案。

有人对 kotlin 和/或 Anko 有相同或类似的问题吗?

更新:我自己找到了解决方案,请在下面查看我的回答以获得解释。

最佳答案

谢谢大家的帮助。我自己弄明白了,所以我发布了这个答案,以防万一其他人遇到这个问题。

TL;DR:context 丢失,因此 uiThread 不会执行

解决方法:我偶然发现了这个 post其中提到了 uiThread 方法的一个重要特征:

Basically you have an async function that will execute it’s code in another thread, and will give the chance of returning main thread using uiThread. async is an extension function implemented for Context, and will use a weak reference of it, so it won’t prevent GC from releasing its memory.

经过进一步调查,我在解析完成后发现了以下日志,并且应该调用 uiThread 的位置:

I/art: Background partial concurrent mark sweep GC freed 30879(16MB) AllocSpace objects, 16(2MB) LOS objects, 40% free, 16MB/27MB, paused 2.123ms total 196.372ms

所以看起来确实有一些 GC 操作,这可能会或可能不会释放 context

为了防止这种情况,我使用了 Ankos runOnUiThread,它可以在给定的上下文引用中调用:

// Asynchronously parse server response
doAsync {
val itemlist = parseResponse(response)
context.runOnUiThread {
Otto.INSTANCE.post(UpdateRedeemedVoucherViewsEvent(itemlist))
}
}

据我所知,这似乎已经成功了。

关于android - Anko 的 uiThread 偶尔不会被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46795795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com