问题
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.
回答1:
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.
回答2:
No, you can't access them outside the UI thread. Very few UI elements can be accessed from a non-UI thread with one being ProgressBar.
回答3:
You can access UI elements in a separate thread but you cannot update them
The only way you can update a UI element in a non-UI thread would be to have a callback to the UI thread in the separate thread using runOnUiThread
or using a Handler
aside from that you cannot make changes to a UI element in a separate thread
回答4:
Variables are not to be accessed outside the UiThread. If you'd like to make modifications from outside the UiThread use :
Activity.runOnUiThread(Runnable)
Some "post" method that stores modifications waiting for the UiThread to treat them. You can use a
BlockingQueue
for example. Have a look atjava.util.concurrent
packageIn some very rare cases the modification of a variable outside the UiThread cannot produce errors in which case it is safe to access it out of the UiThread. In other cases variables should be private, and attempts to access them outside the UiThread should raise
IllegalStateException
or something like that.
来源:https://stackoverflow.com/questions/18702291/using-variables-on-ui-thread-from-worker-thread