我有一个后台线程,用于创建套接字连接,并根据MainActivity的请求将数据发送到套接字。以下代码是我的沟通主题的一部分:
public class networkTask extends Thread {
Bundle inB = new Bundle();
// variables, etc
private Handler inHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
inB = msg.getData();
switch (msg.arg1) {
case 1:
Log.i ("networkTask", "received CONNECT request");
connect();
break;
case 2:
Log.i ("networkTask", "received SEND request");
sendData(inB);
break;
default:
break;
}
else
}
public void run() {
Looper.prepare();
Log.i("networkTask", "launched");
Looper.loop();
}
public Handler getHandler() {
return inHandler;
}
}
我的MainActivity onCreate()包含:
Log.i(TAG, "create NetworkTask");
netComms = new networkTask();
netComms.start();
然后,当我想发送网络流量时,我有:
Handler outHandler = networktask.getHandler();
Message msg = outHandler.obtainMessage();
myB.putString("out_pack", "connect");
msg.setData(myB);
msg.arg1 = 1;
Log.i(TAG, "sending CONNECT request");
outHandler.sendMessage(msg);
当我尝试运行此代码时,我得到 NetworkOnMainThreadException 。
查看logcat输出消息的PID / TID如下:
PID TID
1585 1585 MainActivity create
1585 1598 networkTask launched
1585 1585 MainActivity sending CONNECT request
1585 1585 networkTask received CONNECT request
为什么networkTask消息处理程序由MainActivity TID而不是networkTask TID提供服务? (这可能不是正确的询问方式。)