Using variables in the user interface thread from the work line

The Android developer site reports that when working in the user interface thread, two rules must be followed, i.e.

  • Do not block UI thread

  • Do not access Android UI toolkit from outside the user interface *

Does this mean that I can access the variables in the user interface thread from the workflow, that is, not for the user interface toolkit?

If yes, then you need to do some special considerations if the variable is constantly updated, for example, from SensorEventListener . Thanks.

+3
source share
4 answers

Does this mean that I can access the variables in the user interface thread from the workflow, that is, not for the user interface toolkit?

Yes, if they are declared as member variables, you can access them. You can even access values ​​in UI elements, such as using getText() in a TextView , you simply cannot update any UI elements.

Do I need to ask any special considerations if the variable is constantly updated,

If they are updated, you may want to synchronize the variables. A good way to do this would be to use AsyncTask and update the variable in onPostExecute() .

If you are new to using AsyncTask , be sure to review the Documents a few times and understand them.

+2
source

No, you cannot access them outside of the user interface stream. Very few user interface elements can be accessed from a thread other than the UI, with one of them being a ProgressBar.

0
source

You can access the user interface elements in a separate thread, but you cannot update them

The only way to update a user interface element in a thread other than the UI is to have a callback to the user interface thread in a separate thread using runOnUiThread or using Handler , except that you cannot make changes to the user interface element in a separate thread

0
source

Variables should not be accessible outside of UiThread. If you want to make changes outside of using UiThread:

  • Activity.runOnUiThread(Runnable)

  • Some post method that stores modifications awaiting UiThread processing. For example, you can use BlockingQueue . Take a look at the java.util.concurrent package

  • In some very rare cases, changing a variable outside of UiThread cannot lead to errors, in which case it is safe to access it from UiThread. In other cases, the variables should be private, and attempts to access them outside of UiThread should raise an IllegalStateException or something like that.

-1
source

All Articles