我在我的 onCreate 方法中创建线程。我通过线程上的 udp 接收数据。由于某种原因,它不起作用。
private void UdpThread() {
// server will listen to one client
try
{
Thread udpServerThread = new Thread()
{
@Override
public void run()
{
Log.i("rrr","receivePacket3");
try
{
while(true)
{
sleep(1000);
Log.i("rrr","receivePacket2");
String[] recieved = null;
DatagramSocket clientSocket = null;
InetAddress IPAddress = null;
try {
IPAddress = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] receiveData = new byte[1500];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
clientSocket = new DatagramSocket(8086);
Log.i("rrr","receivePacket");
clientSocket.receive(receivePacket);
Log.i("rrr","receivePacket1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
modifiedSentence = new String(receivePacket.getData());
System.out.println("in client receive:" + modifiedSentence);
Log.i("Received data",modifiedSentence);
clientSocket.close();
modifiedSentence = modifiedSentence.trim();
Log.i("Received data",modifiedSentence);
}
} catch (Exception e){
Log.e("UDP", "S: Error", e);
}
}
};
udpServerThread.start();
//udpServerThread.setPriority(Thread.MAX_PRIORITY);
Toast.makeText(this,modifiedSentence,Toast.LENGTH_LONG).show();
}catch (Exception e) {
// TODO: handle exception
Log.e("eeeee",""+e);
e.printStackTrace();
}
}
当控制没有立即从线程返回时我应该怎么做。等到没有收到数据。