从工作线程UI线程中使用变量 [英] Using Variables on UI Thread from Worker Thread

查看:179
本文介绍了从工作线程UI线程中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android开发者网站指出,两个规则必须遵循的UI线程工作时,即,


  1. 不要阻塞UI线程


  2. 不要访问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.,

  1. Do not block the UI thread

  2. 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 using getText() on a TextView you just can't update any of the UI 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 in onPostExecute().

If you aren't familiar with using AsyncTask, make sure you look through the Docs several times and understand them.

这篇关于从工作线程UI线程中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆