Commit a02c0099 authored by akwizgran's avatar akwizgran

Interrupt network thread by closing socket.

parent ac5c4dd2
......@@ -24,6 +24,9 @@ class NetworkClient extends Thread {
private final Logger log;
private final PowerManager.WakeLock wakeLock;
private Socket socket = null; // Locking: this
private boolean closed = false; // Locking: this
NetworkClient(String host, int port, int keepaliveIntervalMs, Context appContext) {
this.host = host;
this.port = port;
......@@ -35,12 +38,26 @@ class NetworkClient extends Thread {
setDaemon(true);
}
synchronized void closeConnection() {
if (socket != null) tryToClose(socket);
closed = true;
}
private synchronized boolean isClosed() {
return closed;
}
private synchronized Socket createSocket() {
socket = new Socket();
return socket;
}
@Override
public void run() {
wakeLock.acquire();
try {
while (!isInterrupted()) {
Socket s = new Socket();
while (!isClosed()) {
Socket s = createSocket();
try {
s.setTcpNoDelay(true);
s.setKeepAlive(true);
......@@ -54,17 +71,13 @@ class NetworkClient extends Thread {
out.flush();
InputStream in = s.getInputStream();
int read = 0;
while (read != -1 && !isInterrupted()) {
while (read != -1) {
wakeLock.release();
read = in.read();
wakeLock.acquire();
if (read == -1) log.log("End of stream");
else log.log("Read keepalive");
}
if (isInterrupted()) {
log.log("Network thread interrupted");
return;
if (read != -1) log.log("Read keepalive");
}
log.log("End of stream");
} catch (IOException e) {
log.log("Network error: " + e);
} finally {
......
......@@ -96,7 +96,7 @@ public class SnoozeService extends Service {
super.onDestroy();
log.log("Service destroyed");
if (alarm != null) alarm.cancelAlarm();
if (networkClient != null) networkClient.interrupt();
if (networkClient != null) networkClient.closeConnection();
if (foreground) stopForegroundService();
unregisterReceiver(receiver);
if (wakeLock != null) releaseWakeLock();
......@@ -164,7 +164,7 @@ public class SnoozeService extends Service {
}
private void startNetworkThread() {
if (networkClient != null) networkClient.interrupt();
if (networkClient != null) networkClient.closeConnection();
String host = getString(R.string.host);
int port = getResources().getInteger(R.integer.port);
networkClient = new NetworkClient(host, port, keepaliveIntervalMs, getApplicationContext());
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment