Android 开发者网站声明在 UI 线程中工作时必须遵循两条规则,即,
不阻塞 UI 线程
不要从 UI 线程外部访问 Android UI 工具包*
这是否意味着我可以从工作线程内访问 UI 线程中的变量,即不是 UI 工具包?
如果是这样,如果变量不断更新(例如,来自 SensorEventListener
),是否需要考虑任何特殊注意事项。谢谢。
最佳答案
Does this mean that I can access variables in the UI thread from within a worker thread, i.e., not UI toolkit?
是的,只要将它们声明为成员变量就可以访问它们。您甚至可以访问 UI
元素中的值,例如在 TextView
上使用 getText()
您只是无法更新任何 UI
元素。
do any special considerations need to be given if the variable is being continually updated,
如果它们正在更新,那么您可能希望有一种同步变量的方法。执行此操作的一个好方法是使用 AsyncTask
并更新 onPostExecute()
中的变量。
如果您不熟悉 AsyncTask
的使用,请务必查看 the Docs多看几遍就明白了。
关于android - 从工作线程在 UI 线程上使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18702291/