Android Beginner, just started not realize that the update UI in Android can only be used UI thread, write a download thread, update Progessbar in the thread, and display the download progress with TextView
public void listenprogress () {
New Thread (New Runnable () {
@Override
public void Run () {
while (Progress < msgservice.max_progress) {
progress = msgservice.getprogress ();
Progressbar.setprogress (progress);
Text.settext ("Download" + Progress + "%");
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
Text.settext ("Download" + Progress + "%");
}
}
}). Start ();
}
Always error only the original thread, created a view hierarchy can touch its views
It was later realized that the UI could not be updated directly on a non-UI line thread. The data in the child thread changes to update the UI of the main thread, typically through a combination of message mechanisms, messages and handler.
However, I continue to test the discovery, the TextView Update commented out (//text.settext ("Download" + Progress + "%"), there is no above error, after the run progress can be updated normally.
The guidelines inside Android are that non-UI threads are not able to modify UI controls inside the UI thread , but why not call the Setprogress method on the main thread without an error, view source code can be found, setprogress will call to private The synchronized void refreshprogress (int id, int progress, Boolean Fromtouch) method first determines whether the current thread is the primary UI thread, or if the main UI thread calls directly The Dorefreshprogress method updates the progress, except that the main UI thread first creates a Refreshprogressrunnable object and then calls the view's post (Runnable action) method to Refreshprogressrunnable the message queue that is placed on the main UI thread waits for processing. On the surface it seems to be a control that modifies the main thread in a non-UI thread, which in fact is not the case. In the same vein, SeekBar and ProgressDialog can also update progress directly on a child thread.
Reference Blog: http://blog.csdn.net/androidzhaoxiaogang/article/details/8136222
Reference Source:
Private synchronized void refreshprogress (int id, int progress, Boolean Fromtouch) {
if (Muithreadid = = Thread.CurrentThread (). GetId ()) {
Dorefreshprogress (ID, progress, fromtouch);
} else {
Refreshprogressrunnable R;
if (mrefreshprogressrunnable! = null) {
Use Cached refreshprogressrunnable if available
R = mrefreshprogressrunnable;
Uncache it
mrefreshprogressrunnable = null;
R.setup (ID, progress, fromtouch);
} else {
Make a new one
R = new Refreshprogressrunnable (ID, progress, fromtouch);
}
Post (R);
}
}
Non-UI thread update UI issues