如果有这么一个需求,需要发送socket消息来通信,但是发socket消息不能阻塞UI线程,需要放到别的线程发。此时HandlerThread就派上大用处了。HandlerThread的作用就是让一个线程不死并且具备不断处理事情的能力。当然,你也可以用Loop+Handler+thread自己来实现一个这样的东西。但是既然安卓系统给做好了HandlerThread让咱们来用,何必重复造轮子呢。
代码如下:
public class SocketHandler extends Handler {
private static final String TAG = "SocketHandler";
private final Client client = new Client();
private static SocketHandler instance;
private SocketHandler() {
}
private SocketHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(TAG, "handleMessage: start");
Log.d(TAG, "handleMessage: " + new String((byte[]) msg.obj));
if (!client.isConnected()) {
client.connect();
}
client.send((byte[]) msg.obj);
Log.d(TAG, "handleMessage: end");
}
public static SocketHandler getInstance() {
if (instance == null) {
synchronized (SocketHandler.class) {
if (instance == null) {
HandlerThread handlerThread = new HandlerThread("launcher.socket", Process.THREAD_PRIORITY_BACKGROUND);
handlerThread.start();
instance = new SocketHandler(handlerThread.getLooper());
}
}
}
return instance;
}
}
使用方法:
SocketHandler.getInstance().sendMessage(message);
这样你就可以在另一个线程发送socket消息了。