<Button
android:id="@+id/send"
android:onClick="sendUDP"
android:clickable="true"
android:focusable="true"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"/>
public synchronized void sendUDP(View view) {
scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
byte[] buf = "hello".getBytes();
DatagramSocket datagramSocket2 = new DatagramSocket();
DatagramPacket datagramPacket2 = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 12345);
datagramSocket2.send(datagramPacket2);
} catch (IOException e1) {
//TODO Auto-generated catch block
e1.printStackTrace();
}
}
}, 1, 1, TimeUnit.SECONDS);
}
如上两段代码,点击button时,函数并不响应。
原因是先前写了button的onclicklistener方法,注释掉即可。
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// //sendMessage();
// //sendUDP("hello");
// }
// });