Directory:
Basic knowledge:
1. Android Process and threading model
2. The main thread of the Android UI (or called a threading security issue)
Knowledge points involved:
Introduction of Handler
Handler usage One: Sub-threading Transaction (background work), after the completion of the work, in the child thread through the handler message, notifies the UI thread to update the UI control, the UI update action is handled by the handlemessage of handler in the main thread.
How to use Handler II: Handler + handlerthread
Basic knowledge:
1. Android Process and threading model
Each Android application runs in a user process with a separate user ID to ensure that each application's data and programs are isolated from each other.
Reference: http://www.cnblogs.com/Hendy2014/articles/android_process_model.html
2. The main thread of the Android UI (or called a threading security issue)
What is the UI main thread? What is Android's single-threaded model? What is the thread safety issue of Android?
Reference:
Http://www.cnblogs.com/yaozhenfa/p/np_android_Handler.html
Http://www.cnblogs.com/dawei/archive/2011/04/09/2010259.html
Knowledge points involved:
Android.os.Handler, Android.os.Handler.Callback
Looper,
Thread, Runnable
message, Message queue
Introduction of Handler
Because of the aforementioned Android process model and threading model (UI thread, thread safety issues), Android provides some resolution mechanisms, handler is one of them.
Explanation: When the application starts, Android first turns on a main thread (that is, the UI thread), the main thread is the UI control in the management interface, for event distribution, for example, if you click on a button, Android will distribute the event to the button, To respond to your actions. If you need a time-consuming operation at this time, for example: network read data, or read a large local file, you can not put these operations in the main thread, if you put in the main thread, the interface will appear suspended animation, if 5 seconds has not been completed, you will receive an Android system error message Force Close. This time we need to put these time-consuming operations on a sub-thread, because the child threads involve UI updates, the Android main thread is not secure, that is, the update UI can only be updated in the main thread, and the operations in the child threads are dangerous. At this time, handler appeared to solve this complex problem, because handler runs in the mainline approached (UI thread), it and the child thread can pass the data through the Message object, at this time, the handler undertakes to accept the child thread to pass over ( The child thread uses the Sedmessage () method to transmit the message object, which contains data, which is placed in the main thread queue and updated with the main thread. (Quoted from: http://www.cnblogs.com/dawei/archive/2011/04/09/2010259.html)
Handler has two kinds of message methods to solve the inter-thread communication and operation problems, one is the Handler.sendmessage () series method, the second is the Handler.post (runnble) series method, but deep handler source code, Will find it is one thing.
handler Use one: sub-Threading transaction (background work), after the completion of the work, in the child thread through the handler message, notifies the UI thread to update the UI control, by the main thread of the The handler Handlemessage handles UI update actions.
, the handler post is an asynchronous operation.
, two queues, post thread to column, message queue
Handler how to use a model diagram
public class Handlertestactivity extends Activity {private TextView TV; private static final int UPDATE = 0; Private Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {// TODO receives the message and goes to update the control content on the UI thread if (msg.what = = Update) {//Bundle B = msg.getdata (); Tv.settext (b.getstring ("num")); Tv.settext (string.valueof (msg.obj)); } super.handlemessage (msg); } }; /** called when the activity is first created. */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); TV = (TextView) Findviewbyid (r.id.tv); New Thread () {@Override public void run () {///TODO sub-thread sends a message via handler to handler received by Han Dler to update the value of TextView try {for (int i = 0; i <; i++) { Thread.Sleep (500); Message msg = new Message (); Msg.what = UPDATE; Bundle B = new bundle (); b.putstring ("num", "Updated value:" + i); Msg.setdata (b); Msg.obj = "Updated Value:" + i; Handler.sendmessage (msg); }} catch (Interruptedexception e) {e.printstacktrace (); }}}.start (); } }
In addition, an example of using the post () method
Package Android.handler;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class HandlerTest Extends activity {/** Called when the activity is first created. */private button Startbutton;private button Endbutton ; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Gets the control object Startbutton = (Button) Findviewbyid (R.id.startbutton) based on the ID; Endbutton = (Button) Findviewbyid (R.id.endbutton); Sets the Listener Startbutton.setonclicklistener (new Startbuttonlistener ()) for the control; Endbutton.setonclicklistener (New Endbuttonlistener ()); } class Startbuttonlistener implements Onclicklistener{public void OnClick (View v) {//Call Handler's post () method, the thread object to be executed is placed Into the queue handler.post (updatethread);} } class Endbuttonlistener implements onclicklistener{public void OnClick (View v) {//calls Handler's Removecallbacks () method to delete thread objects not executed in the queue handler.removecallbacks (updatethread);} }//Create Handler object Handler Handler = new Handler (); Create a new Thread object Runnable updatethread = new Runnable () {//The action to be performed in the run method of the write thread object, public void Run () {System.out.print ln ("Updatethread"); Call Handler's postdelayed () method//The function of this method is to put the thread object to be executed into the queue, after the time is over, run the developed thread object//The first parameter is the runnable type: The thread object to be executed//The second parameter is Lon Type G: Delay time, in milliseconds handler.postdelayed (Updatethread, 3000); } };}
How to use Handler II: Handler + handlerthread
It is equivalent to using the encapsulated Handlerthread to open an asynchronous thread that contains its own Looper object, which is a MessageQueue message mechanism that runs in an asynchronous thread, and when handler is created, Get Looper with the Handlerthread.getlooper () method, use it as a parameter created by handler to bind it to handler, so that the handler message processing ( The Handlemessage or post runnable method) is in the handlerthread of the asynchronous thread.
Example code one:
public class Threaddemo extends Activity {private static final String TAG = "BB"; private int count = 0; Private Handler Mhandler; Private Runnable mrunnable = new Runnable () {public void run () {//for easy viewing, we print it with log LOG.E (TAG, Thread.CurrentThread (). GetId () + "" +count); count++; Settitle ("+count"); Mhandler.postdelayed is performed every 2 seconds (Mrunnable, 2000); } }; @Override public void OnCreate (Bundle savedinstancestate) {log.e (TAG, "Main id" +thread.currentthread (). Geti D () + "" +count); Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Start thread Handlerthread handlerthread = new Handlerthread ("Threadone") via handler; Handlerthread.start (); Mhandler = new Handler (Handlerthread.getlooper ()); Mhandler.post (mrunnable); } @Override Protected void OnDestroy () {//The thread is removed from the current handler mhandler.removecallbacks (mrunnable); Super.ondestroy (); } }
When you create a Handler, if you do not specify a Looper object for it (new Handler (Looper) or Setlooper (Looper)), Handler uses the Looper of the thread that created it by default, Then handler's message processing eventually runs in the thread that created it (the Runnable object in post (), SendMessage () after the Handlemessage () code), to testify to this, the following example, using the UI main thread to create the handler, The Runnable object in its post () and the Handlemessage () code after sendMessage () will run in the UI main thread.
Example one:
public class Threaddemo extends Activity {private static final String TAG = "BB"; private int count = 0; Private Handler Mhandler; Private Runnable mrunnable = new Runnable () {public void run () {//for easy viewing, we print it with log LOG.E (TAG, Thread.CurrentThread (). GetId () + "" +count); count++; Settitle ("+count"); Mhandler.postdelayed is performed every 2 seconds (Mrunnable, 2000); } }; @Override public void OnCreate (Bundle savedinstancestate) {log.e (TAG, "Main id" +thread.currentthread (). Geti D () + "" +count); Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Start thread Mhandler = new Handler () via Handler; Mhandler.post (mrunnable); Mrunnable eventually runs on the UI main thread} @Override protected void OnDestroy () {//To unbind the thread from the current handler//mhandler . Removecallbacks (mrunnable); Super.ondesTroy (); } }
----------------------
Check the gaps: Java thread review
The main thread in the new thread and start (), the same runnable () will print out a different threadid, start after the thread is entered into the threading state machine, the CPU time chip turn to the thread of the time to execute, and then into the start, run, pause, Stop waiting in the state machine. (Thread life cycle, remember?) )
Private Runnable mrunnable = new Runnable () {public void run () { //for easy viewing, we print it with Log log.e (TAG, Thread.curr Entthread (). GetId () + "" +count); count++; Settitle ("+count"); Executes mhandler.postdelayed (mrunnable, +) every 2 seconds; } ; @Override public void OnCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.main); The thread thread = new Thread (mrunnable) is started through handler. Thread.Start (); }
Related blog Posts:
Http://www.cnblogs.com/youxilua/archive/2011/11/25/2263825.html
Http://www.cnblogs.com/yaozhenfa/p/np_android_Handler.html
Other references:
Pro Android 3 This book, which describes the handler is very meticulous.
Handler's understanding and use of a