Java thread to believe that everyone has a certain understanding, this article let us discuss the problem of the thread in Android, the difference between thread and process I will not repeat, interested children shoes can Baidu, explain the very detailed, I believe you can often hear about the thread of things. Let's take a look at it.
Why do you want to know about the threading mechanism of Android? Because Google to improve Android security, require Android4.0 later version, need network access, to declare. We all know that network access is a time-consuming operation, so we need to add network access to the sub-threading, and then thread the data to the main path to display.
Let me give you a brief example of why a child thread cannot make a view update:
@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); TextView=(TextView) Findviewbyid (R.id.textview); /** Child threads cannot be updated with views*/ NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000);//Analog Network loading}Catch(interruptedexception e) {e.printstacktrace (); } textview.settext ("Update View"); }}). Start ();
}
This will cause the system to be strongly retired:
Locat Print error log:
The reason for this error is that because the child thread is unable to update the UI interface, the UI update must be done in the main thread, so this is how to go back to the main thread from the child threads. The method is actually very simple, let's look at two ways to do the above UI update.
Method One: Through Runonuithread (new Runnable () {});
//Update View method one: NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000);//Analog Network loading}Catch(interruptedexception e) {e.printstacktrace (); } //return to main threadRunonuithread (NewRunnable () {@Override Public voidrun () {Textview.settext ("Update View method One"); } }); }}). Start ();
This completes the update of our UI interface.
Method Two: Through the handler class to achieve:
First we need to create a handler object that will update the UI interface with this object.
Create a Handler object
PrivateNew Handler ();
//Update View method two: NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (3000);//Analog Network Load}Catch(interruptedexception e) {e.printstacktrace (); } handler.post (NewRunnable () {@Override Public voidrun () {Textview.settext ("Update View Method Two"); } }); }}). Start ();
Both of these methods are very powerful, I personally prefer the first method, but through the handler UI interface update is very powerful, in a few subsequent summaries, I will introduce you handler in dealing with threading problems in the way and powerful. If you are interested in this you can keep an eye on the update.
Android Thread processing