I have a UDP Server/Client running in background with Service, these are my operations:
- I launch the app
- The Service starts
- I close the app but the Service is running in background (this is what I want)
- I send udp message and the phone receives correctly and answer me
- I don't send messages for about 5 minutes
- I send message, my phone doesn't answer me
- I try to send another message again, my phone now answer
How could it happen? My App seems to sleep and wake up when I send the first message but it could answer only the second or sometimes I need 4-5 messages before get an answer, maybe is this latency or other?
If I flood my App it always will answer me correctly, but if I don't send messages for an amount of time it will cause the problem.
I want my App answer me everytime, even if the app is closed or the phone is locked.
This is my code:
public class UDPListenerService extends Service {
DatagramSocket socket;
private Boolean shouldRestartSocketListen = true;
Thread UDPBroadcastThread;
private void listenAndWaitAndThrowIntent() throws Exception {
try {
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramSocket serverSocket = new DatagramSocket(9876);
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
receiveData = new byte[1024];
}
} catch (Exception e) {
}
}
void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent();
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
shouldRestartSocketListen = true;
startListenForUDPBroadcast();
Log.i("UDP", "Service started");
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
stopListen();
}
void stopListen() {
shouldRestartSocketListen = false;
socket.close();
}
}