Search code examples
androidthread-safetyrunnable

Using Variables on UI Thread from Worker Thread


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.


Solution

  • 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.