Handler异步消息机制关键步骤

public class MainActivity extends AppCompatActivity {

    //Handler在哪个线程new,就默认拥有哪个线程的Looper对象和消息队列
    //主线程的Looper.prepare()和Looper.loop()在主线程创建的时候就默认调用了
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //初始化线程looper对象,包括初始化looper的MessageQueue
                Looper.prepare();
                //new Handler,此时会将looper中的MessageQueue塞给Handler
                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Toast.makeText(MainActivity.this, msg.what + "", Toast.LENGTH_LONG).show();
                    }
                };
                //不断循环监听是否有新消息入队,有就调用msg.target(Handler)的dispatchMessage()回调到handleMessage()
                Looper.loop();

            }
        }).start();

        Message message = mHandler.obtainMessage();
        message.what = 100;
        //将消息入队
        mHandler.sendMessage(message);
    }
}

你可能感兴趣的:(Handler异步消息机制关键步骤)