从工作线程UI线程中使用变量 [英] Using Variables on UI Thread from Worker Thread
问题描述
Android开发者网站指出,两个规则必须遵循的UI线程工作时,即,
-
不要阻塞UI线程
-
不要访问Android的UI工具包UI线程之外*
这是否意味着我可以访问的在UI线程变量的从辅助线程内,即不UI工具包?
如果是这样,做任何特殊的考虑需要给予如果变量正在不断更新,例如从 SensorEventListener
。谢谢你。
这是否意味着我可以访问的变量在UI线程从辅助线程内,即不UI工具包?
块引用>是的,只要它们被声明为成员变量,那么你可以访问它们。你可以在
UI
元素,如使用的getText()
在TextView的<甚至访问值/ code>你就不能更新任何
UI
元素。
做任何特殊的考虑需要给予如果变量正在不断更新,
块引用>如果正在更新他们,那么你可能需要有同步变量的一种方式。要做到这一点的一个好方法是使用一个
的AsyncTask
和更新onPostExecute变量()
。如果您不熟悉使用
的AsyncTask
,请确保您通过的的文档几次,理解他们。The Android Developers site states that two rules must be followed when working in the UI thread, i.e.,
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread*
Does this mean that I can access variables in the UI thread from within a worker thread, i.e., not UI toolkit?
If so, do any special considerations need to be given if the variable is being continually updated, e.g., from a
SensorEventListener
. Thanks.解决方案Does this mean that I can access variables in the UI thread from within a worker thread, i.e., not UI toolkit?
Yes, as long as they are declared as member variables then you can access them. You can even access values in
UI
elements such as usinggetText()
on aTextView
you just can't update any of theUI
elements.do any special considerations need to be given if the variable is being continually updated,
If they are being updated then you may want to have a way of syncing the variables. A good way to do this would be to use an
AsyncTask
and update the variable inonPostExecute()
.If you aren't familiar with using
AsyncTask
, make sure you look through the Docs several times and understand them.这篇关于从工作线程UI线程中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!