Simple use of Android Handler and Loop, and androidhandler
1. Communication between subthreads and subthreads
package lib.com.myapplication;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.support.v7.app.AppCompatActivity;public class MainActivity extends AppCompatActivity { private Handler handler1 ; private Handler handler2 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new MyThread1().start(); new MyThread2().start(); } class MyThread1 extends Thread { @Override public void run() { super.run(); Looper.prepare(); handler1 = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); System.out.println( "threadName--" + Thread.currentThread().getName() + "messageWhat-"+ msg.what ); } }; try { sleep( 3000 ); } catch (InterruptedException e) { e.printStackTrace(); } handler2.sendEmptyMessage( 2 ) ; Looper.loop(); } } class MyThread2 extends Thread { @Override public void run() { super.run(); Looper.prepare(); handler2 = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); System.out.println( "threadName--" + Thread.currentThread().getName() + "messageWhat-"+ msg.what ); } }; try { sleep( 4000 ); } catch (InterruptedException e) { e.printStackTrace(); } handler1.sendEmptyMessage( 5 ) ; Looper.loop(); } }}
Note:
1. Call logoff classprepare()Method To create a message loop for the current thread, callloop()Method to process the information until the cycle ends.
2. Handler has several construction reloads. If the logoff object parameter is not provided during the construction, the logoff object of the current thread will be obtained, and the message loop of the current thread will be used as the message loop associated with the Handler.
3,In the message processing mechanism, messages are stored in a message queue, and threads enter an infinite loop around the queue until the program exits.
If there is a message in the queue, the thread will extract the message and distribute it to the corresponding Handler for processing;
If no message exists in the queue, the thread enters the idle waiting state and waits for the next message to arrive.