Handler主线程向子线程发消息

一、简介:

说说主线程向子线程发送消息,如果handler是在主线程中创建,那没什么好说的,主线程会自动创建Looper和MessageQueen,但是子线程却不会创建了,不多说,直接上代码

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int SEND_MESSAGE = 10;

    private Handler mHandler;

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

        new Thread(new MyRunnable()).start();

        findViewById(R.id.send_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = Message.obtain();
                msg.what = SEND_MESSAGE;
                msg.obj = "主线程向子线程发送新的消息啦";
                mHandler.sendMessage(msg);
            }
        });
    }

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            //建立消息循环的步骤
            Looper.prepare();//1、初始化Looper
            mHandler = new Handler() {//2、绑定handler到CustomThread实例的Looper对象
                public void handleMessage(Message msg) {//3、定义处理消息的方法
                    if (msg.what == SEND_MESSAGE) {
                        Log.i(TAG, "handleMessage:---->" + msg.obj);
                    }
                }
            };
            Looper.loop();//4、启动消息循环
        }
    }
}

你可能感兴趣的:(Handler主线程向子线程发消息)