Interrupt device threads on stop

The (non-daemon) threads were not interrupted on video stream stopped,
leaving the server process alive.

Interrupt them to wake up their blocking call so that they terminate
properly.

Refs #1992 <https://github.com/Genymobile/scrcpy/issues/1992>
This commit is contained in:
Romain Vimont 2021-01-01 12:26:44 +01:00
parent 3ba51211d6
commit 90f8356630

View file

@ -58,12 +58,14 @@ public final class Server {
ScreenEncoder screenEncoder = new ScreenEncoder(options.getSendFrameMeta(), options.getBitRate(), options.getMaxFps(), codecOptions, ScreenEncoder screenEncoder = new ScreenEncoder(options.getSendFrameMeta(), options.getBitRate(), options.getMaxFps(), codecOptions,
options.getEncoderName()); options.getEncoderName());
Thread controllerThread = null;
Thread deviceMessageSenderThread = null;
if (options.getControl()) { if (options.getControl()) {
final Controller controller = new Controller(device, connection); final Controller controller = new Controller(device, connection);
// asynchronous // asynchronous
startController(controller); controllerThread = startController(controller);
startDeviceMessageSender(controller.getSender()); deviceMessageSenderThread = startDeviceMessageSender(controller.getSender());
device.setClipboardListener(new Device.ClipboardListener() { device.setClipboardListener(new Device.ClipboardListener() {
@Override @Override
@ -79,12 +81,19 @@ public final class Server {
} catch (IOException e) { } catch (IOException e) {
// this is expected on close // this is expected on close
Ln.d("Screen streaming stopped"); Ln.d("Screen streaming stopped");
} finally {
if (controllerThread != null) {
controllerThread.interrupt();
}
if (deviceMessageSenderThread != null) {
deviceMessageSenderThread.interrupt();
}
} }
} }
} }
private static void startController(final Controller controller) { private static Thread startController(final Controller controller) {
new Thread(new Runnable() { Thread thread = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
@ -94,11 +103,13 @@ public final class Server {
Ln.d("Controller stopped"); Ln.d("Controller stopped");
} }
} }
}).start(); });
thread.start();
return thread;
} }
private static void startDeviceMessageSender(final DeviceMessageSender sender) { private static Thread startDeviceMessageSender(final DeviceMessageSender sender) {
new Thread(new Runnable() { Thread thread = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
@ -108,7 +119,9 @@ public final class Server {
Ln.d("Device message sender stopped"); Ln.d("Device message sender stopped");
} }
} }
}).start(); });
thread.start();
return thread;
} }
private static Options createOptions(String... args) { private static Options createOptions(String... args) {