Handler线程间通信实例

发布时间 2023-10-18 17:02:40作者: 余黎明

1、需求背景

在开发中,socket网络通信需要放到子线程做

2、代码实现

1)定义一个SendHandler类继承Handler

public static SendHandler mHandler;
private HandlerThread mHandlerThread;
public class SendHandler extends Handler{
        private String TAG = "lemon";
        public SendHandler(Looper looper) {
            super(looper);
        }
        public void handleMessage(Message msg){
            Log.i(TAG, "handlermessage =" + msg.what);
            try {
                if (mSocket != null && mSocket.isConnected()) {
                    if (pw != null) {
                        Log.i(TAG, "handlermessage in newThread is " + msg.what);
                        String res = String.valueOf(msg.what);
                        Bundle bundle = msg.getData();
                        Object velocityX = bundle.get("velocityX");
                        Object velocityY = bundle.get("velocityY");
                        Log.i(TAG, "handlermessage in newThread x is " + bundle.get("velocityX") + ",y is " + bundle.get("velocityY"));
                        if (velocityX != null && velocityY != null) {
                            res = res + " " + bundle.get("velocityX") + " " + bundle.get("velocityY");
                        }
                        pw.println(res);
                        pw.flush();
                    }
                }
            } catch (Exception e) {
                Log.i(TAG, "Exception is" + e);
            }
        }
    }

2)Handler线程和Hadnler对象在初始化的时候实例化

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_touch);
        mHandlerThread = new HandlerThread("TrackPad_thread");
        mHandlerThread.start();
        mHandler = new SendHandler(mHandlerThread.getLooper());
    }

3)主线程调用mHandler.sendMessage到子线程handleMessae处理

mHandler.sendMessage(message)