First, why write this article
?? Do you often see many books saying that you cannot manipulate the UI in a child thread, or you will get an error. Do you also encounter the following doubts (see code below):
@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); TV = (TextView) Findviewbyid (r.id.tv); Thread.CurrentThread (). SetName ("Uithread");NewLooperthread (). Start (); }Private class looperthread extends Thread { @Override Public void Run() {Thread.CurrentThread (). SetName ("Otherthread"); Tv.settext ("Other thread"); } }
?? It does operate the UI in a child thread, but he doesn't give an error, why? Isn't that just a contradiction to the book? At that time myself also met this problem, so with this blog, thanks to the network of those predecessors of the selfless sharing, now will own the collation and thinking record down.
Second, the introduction
?? In the Android development process, it is often necessary to update the UI of the interface. The update UI is to be updated by the main thread, which is the UI thread update. If you update the page directly in a thread other than the main thread, the error often appears. Throw exception: Android.view.viewroot$calledfromwrongthreadexception:only The original thread that created a view hierarchy can tou Ch its views. How to solve it? Below I will detail how the child threads update the UI:
Third, the child thread update UI Method 1, with Handler+message
?? The main thread defines handler, and the child threads send messages informing handler to complete the UI update.
Mhandler =NewHandler () {@Override Public void Handlemessage(Message msg) {//Operator InterfaceMytext.settext (information from the network);Super. Handlemessage (msg); } }; Public class MyThread extends Thread { Public void Run() { ? ? ?//time-consuming Operation? ? ? ? Loadnetwork (); Message msg =NewMessage (); Mhandler.sendmessage (msg);//Send a message to handler,} }
The schematic diagram of the handler is as follows:
2. Update with Runonuithread
?? This is the best use, where to refresh the page, you can write as follows.
new Thread() { publicvoidrun() { //这儿是耗时操作,完成之后更新UI; runOnUiThread(new Runnable(){ @Override publicvoidrun() { //更新UI imageView.setImageBitmap(bitmap); } }); } }.start();
?? This method is more flexible to use, but if the thread is defined elsewhere, the activity object (passed through the constructor) needs to be passed.
3, View.post (Runnable R)
?? Method Explanation: Derive your subclass from Runnable and reload the Run () method. Then call View.post (myrunnableobj) to add your Runnable object to the UI thread to run.
publicvoidonClick( View v ) { newnew Runnable() { publicvoidrun() { // 耗时操作 ? ? ? ? ? ? loadNetWork(); ? new Runnable() { myText.setText( 来自网络的信息); }); } }).start(); }
?? This method is simpler, but it needs to pass the view that you want to update. Note: The post function, which is passed a runnable interface (you know runnable is not a thread this you must be separated from the thread section).
4. Using Asynchronous tasks
//ui thread execute new Downloadimagetask (). Execute ( "www.91dota.com" ); private class downloadimagetask extends asynctask { protected string doinbackground (String ... url) {return loaddataformnetwork (url[0 ]); //background time-consuming operation } protected void onpostexecute (String result) {Mytext.settext (result); //get information from the Network Refresh page }}
Application situations
- If it is a background task, such as a download task, you need to use Asynctask.
- If you need to pass information such as status value, such as a socket connection in Bluetooth programming, you need to use the status value to prompt the connection state and do the corresponding processing, you need to use Handler + thread method;
- Requires another thread to process the data to avoid blocking the UI thread, such as an IO operation or a loop, you can use Activity.runonuithread ();
- If you simply want to update the UI without multithreading, use View.post ().
Iv. the illusion of updating the UI in a child thread
?? Back to the beginning of the problem, the child thread update UI was successful, not actually. There is another way of doing this: using an interface callback in a child thread to update the UI in the activity, it is also a disguised way to update the UI in a child thread. Why did it succeed? The reason for refining point is that: This anomaly is the Android source code in the detection settings thrown, if the detection method is not executed will not error. OnCreate method in the thread update UI is not an error, because the view has not yet come out.
For more in-depth explanations please refer to:
Http://www.2cto.com/kf/201111/111172.html
http://blog.csdn.net/imyfriend/article/details/6877959
Http://doc.okbase.net/aigestudio/archive/127460.html
http://blog.csdn.net/zhaokaiqiang1992/article/details/43410351
Http://blog.csdn.net/aigestudio/article/details/43449123
http://javapolo.iteye.com/blog/1343583
http://blog.csdn.net/androidzhaoxiaogang/article/details/8136222
V. Overview
?? Sometimes using a thread to update the UI directly without error, but it is not recommended, Google's Android underlying code in the update UI to detect threads, the reason is to avoid us in the non-UI thread to update the UI directly, although we exploit, can not report the exception, But that's not a good way. The reason for Google's design is that it makes the UI thread a little bit more purely a matter of interface, and if the UI thread executes a time-consuming operation, it will feel like a lag when doing UI work. That is, from the perspective of updating the view, it is better to be the UI thread, and the non-UI thread is not unable to update the UI.
An analysis of how to update the UI of the Android neutron thread