可以从 AsyncTask.doInBackground() 读取 UI 线程中的值
在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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
理想情况下,您不要触及
AsyncTask
的doInBackground()
内的活动。原因:配置更改(例如,屏幕旋转)。当线程运行时,活动可能会被替换,因此您可能会从错误的活动中读取内容。如果您遵循我在
Ideally, you don't touch an activity within
doInBackground()
of anAsyncTask
. 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 theAsyncTask
, 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.