您好,我的服务有问题。我正在制作一个实现 UDPServer 并登录主要活动接收到的数据包的应用程序。我希望即使活动关闭也能启动服务,所以我认为我必须使用服务。这是真的吗?我已经实现了一个应用程序可以毫无问题地实现音乐播放器服务,但是当在服务 onStart 函数中插入 UDP 服务器的代码时,我的应用程序崩溃了。这是关于udp服务器的代码:
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
//Create the socket using the serverAddress
//notifica("STARTING SERVER!", "UDP***Creating server" );
//System.out.println("UDP***Creating server");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);
//create a buffer to copy packet contents into
byte[] buf = new byte[260];
//create a packet to receive
DatagramPacket packet = new DatagramPacket(buf, buf.length);
notifica("START!", "Server started!" );
while(true) {
try{
socket.receive(packet);
System.out.println("UDP***" + new String(packet.getData()));
notifica("RECEIVED!", new String(packet.getData()) );
} catch (Exception e) {
notifica("EXC_INT:", "UDP Received Exception! " + e.toString() );
}
}
我认为问题出在命令上:
socket.receive(packet);
它阻止执行并等待读取内容。我希望主程序不会阻止等待服务。
我尝试在服务中插入超时和睡眠命令,但没有任何结果:
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
//Create the socket using the serverAddress
//notifica("STARTING SERVER!", "UDP***Creating server" );
//System.out.println("UDP***Creating server");
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);
//create a buffer to copy packet contents into
byte[] buf = new byte[260];
//create a packet to receive
DatagramPacket packet = new DatagramPacket(buf, buf.length);
notifica("START!", "Server started!" );
while(true) {
try{
socket.setSoTimeout( 100 );
socket.receive(packet);
System.out.println("UDP***" + new String(packet.getData()));
notifica("RECEIVED!", new String(packet.getData()) );
} catch (SocketTimeoutException e) {
//notifica("EXC:", "UDP No data received!" );
//Toast.makeText(getApplicationContext(), "UDP No data received!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
notifica("EXC_INT:", "UDP Received Exception! " + e.toString() );
}
try{
Thread.sleep(30000);
} catch (Exception e) {
notifica("EXC_INT_TIMER:", "Thread sleep exc! " + e.toString() );
}
}
谢谢!