The previous article has simply introduced to you about the use of handler, this article we will discuss the advanced use of handler, the previous article we just simple UI update, this article we come together to discuss how to send the thread of data sent to the main thread for processing, For this problem, I think there must be a lot of small partners have been troubled, in fact, this is very simple, I have the same feeling as everyone else in the thread from the sub-threading to the main thread is not possible, but now can really negate my previous view, the child thread to the main thread to send data is completely no problem. Well, don't say much nonsense, let's discuss it together.
1. We use handler and message to complete:
/ ** Pass int type data*/ NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } Message msg=NewMessage (); //mes.arg1, MES.ARG2, Mes.what: can only transfer int type dataMSG.ARG1 = 1; Msg.arg2= 2; Msg.what= 3; Handler.sendmessage (msg); }}). Start ();
Process the data sent by the message:
//declares a handler object and implements the Handlemessage () method in itPrivateHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {if(msg.what==3) {Textview.settext ("MSG.ARG1:" +msg.arg1+ "MSG.ARG2:" +msg.arg2); }Else{ if(msg.what==2) { person person=(person) msg.obj; Textview.settext ("Name:" +person.getname () + "Gender:" +person.getsex () + "Age:" +person.getyear ()); } } }; };
2, the use of the message:
The above we send to handler data are int data, which certainly does not meet our daily needs, how to send a message to handler an object data? Don't worry, people. The message encapsulates an obj () method for us to pass the data.
NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } Person Person=NewPerson (); Person.setname ("Xiao Wang"); Person.setsex ("Girl"); Person.setyear (22); Message msg=NewMessage (); Msg.what= 2; Msg.obj=Person ; Handler.sendmessage (msg); }}). Start ();}
Person is an object that I encapsulate:
Public classPerson {PrivateString name; PrivateString sex; Private intYear ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Getsex () {returnsex; } Public voidsetsex (String sex) { This. Sex =sex; } Public intgetYear () {returnYear ; } Public voidSetyear (intYear ) { This. Year =Year ; }}
The processing of the data for this message has been shown in the above for everyone.
See here you are not already feel handler strong, indeed when we deal with multithreading problems, handler is very convenient, interested can continue to pay attention to yo, the next more exciting.
The handler of the Android threading process