Skip to content
Snippets Groups Projects
Commit f33e7a29 authored by akwizgran's avatar akwizgran
Browse files

Close socket if connection is idle for two keepalive periods.

parent 02d5eb22
No related branches found
No related tags found
No related merge requests found
......@@ -27,6 +27,8 @@ class NetworkClient extends Thread {
private Socket socket = null; // Locking: this
private boolean closed = false; // Locking: this
private volatile long lastActive;
NetworkClient(String host, int port, int keepaliveIntervalMs, Context appContext) {
this.host = host;
this.port = port;
......@@ -35,6 +37,7 @@ class NetworkClient extends Thread {
PowerManager pm = (PowerManager) appContext.getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PARTIAL_WAKE_LOCK, LOCK_TAG);
wakeLock.setReferenceCounted(false);
lastActive = System.currentTimeMillis();
setDaemon(true);
}
......@@ -52,6 +55,14 @@ class NetworkClient extends Thread {
return socket;
}
void onAlarm() {
long inactive = System.currentTimeMillis() - lastActive;
if (inactive > 2 * keepaliveIntervalMs) {
log.log("Inactive for " + (inactive / 1000) + " seconds, closing socket");
closeConnection();
}
}
@Override
public void run() {
wakeLock.acquire();
......@@ -63,18 +74,24 @@ class NetworkClient extends Thread {
s.setKeepAlive(true);
s.setSoTimeout(SOCKET_TIMEOUT_MS + keepaliveIntervalMs);
log.log("Connecting to " + host + ":" + port);
lastActive = System.currentTimeMillis();
s.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
log.log("Requesting keepalives every "
+ (keepaliveIntervalMs / 1000) + " seconds");
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.writeShort(keepaliveIntervalMs / 1000);
out.flush();
lastActive = System.currentTimeMillis();
InputStream in = s.getInputStream();
int read = 0;
while (read != -1) {
wakeLock.release();
read = in.read();
wakeLock.acquire();
try {
read = in.read();
} finally {
wakeLock.acquire();
}
lastActive = System.currentTimeMillis();
if (read != -1) log.log("Read keepalive");
}
log.log("End of stream");
......@@ -91,7 +108,7 @@ class NetworkClient extends Thread {
}
}
} finally {
if (wakeLock.isHeld()) wakeLock.release();
wakeLock.release();
}
}
......
......@@ -85,8 +85,12 @@ public class SnoozeService extends Service {
} else if (ACTION_ALARM.equals(i.getAction())) {
AlarmType alarmType = AlarmType.valueOf(i.getStringExtra(EXTRA_ALARM_TYPE));
log.log("Alarm " + alarmType);
if (alarm == null) log.log("Service recreated by alarm");
else setAlarm();
if (alarm == null) {
log.log("Service recreated by alarm");
} else {
if (networkClient != null) networkClient.onAlarm();
setAlarm();
}
}
return START_NOT_STICKY; // Don't restart automatically if killed
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment