protected void onCreate(Bundle savedInstanceState) {
...
byte sendData[] = new byte[1024];
String sentence = "Hey!";
sendData = sentence.getBytes();
int ret = 0;
try {
DatagramSocket socket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("192.168.0.11");
DatagramPacket sendPacket = new
DatagramPacket(sendData,4, IPAddress,4202);
socket.send(sendPacket);
socket.close();
}
如果socket.send
被注释掉,代码就可以使用。
清单包含:
uses-permission android:name="android.permission.INTERNET"
谢谢。
答案 0 :(得分:0)
如果你运行socket.send,如果你在onCreate方法或UI线程上运行该代码,它将给出NerworkOnMainThread异常,
尝试创建类似
的线程 private LinkedBlockingQueue<DatagramPacket> writeQueue = new LinkedBlockingQueue<DatagramPacket>();
private Thread sendThread = new Thread() {
private boolean shouldStop = false;
@Override
public void run() {
while (!shouldStop) {
if ((finshed) && (writeQueue.size() == 0)) {
return;
}
try {
DatagramPacket packet = writeQueue.take();
if (socket == null) {
shouldStop = true;
} else {
socket.send(packet);
}
} catch (InterruptedException e) {
shouldStop = true;
} catch (IOException e) {
e.printStackTrace();
shouldStop = true;
}
}
}
};