我目前正在尝试通过UDP接收数据报包。我使用的代码是Java(适用于Android)。我已经完成的是创建一个界面,用户将点击“开始”按钮。从那里开始按钮将开始接收数据报包。下面我已经开始编码,但我不确定我做错了什么?我想将数据显示为编辑文本。我是否必须创建开始活动的意图?
任何建议或帮助将不胜感激。
btnStart = (Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new OnClickListener(){
public void onClick (View v){
txtData = (EditText)findViewById(R.id.txtData);
//Log.v("EditText", txtData.getText().toString());
try {
final int PORT = 50009;
DatagramSocket dsocket = new DatagramSocket (PORT);
byte[] buffer = new byte [1024];
//loop forever, waiting to receive packets and printing them
while(true){
dsocket = new DatagramSocket(PORT);
DatagramPacket packet = new DatagramPacket (buffer, buffer.length);
//wait to receive a datagram
dsocket.receive(packet);
//converts the contents to a string and displays them
//String msg = new String(buffer, 0, packet.getLength());
//Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
buffer =packet.getData();
dsocket.close();
}}
catch (SocketException e){
Log.v("SocketExceptionOccurred", e.toString());
e.printStackTrace();
}catch (IOException e){
Log.v("IOExceptionOcurred", e.toString());
e.printStackTrace();
}
}});
答案 0 :(得分:0)
嗯......您没有给我们任何类型的错误消息。不过,我绝对可以看到两件错误的事情:
while (true)
循环将挂起UI线程。你不能这样做查看Service类。您可能希望在IntentService中进行联网。