Running on UI Thread from a view
I have a custom view that contains several views in itself. I've made it so that when one of the views inside this container view is clicked, it will run a "timer" thread that needs to update the a TextView, also inside the container view, every second. My problem occurs when I want to u开发者_Python百科pdate the TextView every second. Apparently, it wasn't as easy as I had thought. I implemented Runnable inside my container view like so, and executed the thread when the button was clicked to start the timer:
public void run() {
while(runnning) {
// if one second has passed, update the Textview
}
}
I get the typical cannot-touch-views-outside-hierarchy exception, which basically means it's not running on the UI thread. I don't want to use post(Runnable)
here because I don't want to wait all the way till the end of the thread to update one second. It's also not practical for me to pass the entire Activity it's in to itself to run runOnUiThread(Runnable)
. So could someone tell me how I might go about doing this? If anyone needs clarification, please let me know!
You want to use an Android AsyncTask. Its an Android specific construct for just this type of periodic GUI updating while waiting for something to finish.
Do your timer in doInBackground and have it call publishProgress whenever you want it to update the GUI. Then in onProgressUpdate just update the GUI. onProgressUpdate runs on the GUI thread and doInBackground runs on a background thread automaticially.
what do you mean by passing entire activity ?? you can achieve it by creating a timer thread inside this thread whenever you want to update UI (like after 1 sec.) call runOnUIThread() .
精彩评论