When inter-thread communication, such as Android in common update UI, related to the communication between the child thread and the main thread, implementation is Handler + Looper, but to their own manual Looper, is not recommended, so Google encapsulates HandlerThread class (similar to AsyncTask class).
Child thread executing the task to send a message to the sub-handler thread, the child thread Handler reuse HandlerThread send a message to the main thread update ui
public class the MainActivity the extends AppCompatActivity { the TextView the textView; the Button Button; MainHandler MainHandler; protected void the onCreate (the Bundle savedInstanceState) { Super .onCreate (savedInstanceState); the setContentView (R.layout.activity_main); the textView = the findViewById (R.id.text); the Button = findViewById (R.id.button); // this is the main thread Handler instance if there is a knowledge that is passed when there is no new Handler looper to her, he would go to the default contact looper thread currently running mainHandler = new new MainHandler ( the this ); HandlerThread HandlerThread = new new HandlerThread ( "First" ); handlerThread.start (); // This is the handler child thread the looper handlerThread incoming links of Final Handler childHandler = new new Handler (handlerThread.getLooper ()) { int COUNT = 0 ; @Override public void the handleMessage (the Message MSG) { Super .handleMessage (MSG); System.out.println ( "child threads Handler received data will now send data to the main thread of execution" + . Thread.currentThread () getName ( )); // send a message to the main thread of her handler ui update Message.obtain (MainHandler,. 1, ++ COUNT) .sendToTarget (); } }; // Open a thread of the call information transmission childHandler button.setOnClickListener ( new new View.OnClickListener () { @Override public void the onClick (View V) { new new the thread ( new new the Runnable () { @Override public void RUN () { System.out.println ( "child thread sending data" + Thread.currentThread () getName ());. // transmitted to the handler handlerThread childHandler.sendEmptyMessage (. 1 ); } .}) Start (); } }); } // This is the main thread of this form defined Handler, memory leaks can be prevented class MainHandler the extends Handler { Private WeakReference <the MainActivity> mainActivityWeakReference; MainHandler (the MainActivity MainActivity) { the this .mainActivityWeakReference = new new WeakReference <> (MainActivity); } @Override public void the handleMessage (the Message MSG) { super.handleMessage(msg); mainActivityWeakReference.get().textView.setText(msg.obj + ""); } } }