可以从 AsyncTask.doInBackground() 读取 UI 线程中的值

发布于 2024-10-31 12:28:22 字数 153 浏览 4 评论 0原文

在Android中,可以从AsyncTask.doInBackground()读取UI线程中存在的值(例如Activity子类的成员字段),而不是尝试写入它们吗?或者应该只在 AsyncTask.onPostExecute() 中完成读取?

In Android, is it OK to read values that exist in the UI thread (e.g. an Activity subclass's member fields) from an AsyncTask.doInBackground(), just not try to write them? Or should reading only be done in AsyncTask.onPostExecute()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_蜘蛛 2024-11-07 12:28:22

理想情况下,您不要触及 AsyncTaskdoInBackground() 内的活动。原因:配置更改(例如,屏幕旋转)。当线程运行时,活动可能会被替换,因此您可能会从错误的活动中读取内容。

如果您遵循我在

Ideally, you don't touch an activity within doInBackground() of an AsyncTask. The reason: configuration changes (e.g., screen rotations). The activity might be replaced while the thread is chugging along, and therefore you might wind up reading from the wrong activity.

If you follow the recipe I outline in this answer over yonder, and you synchronize access to the Activity being held by the AsyncTask, you'll get as good of results as possible. Of course, you will also have to deal with thread safety of whatever it is you're reading ("e.g. an Activity subclass's member fields"), as they may or may not be thread-safe already.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文