I have been seeing issues similar to
JENKINS-10639 where the android emulator does not shutdown.occasionally. I have instrumented the android-emulator plugin to try to get some information on what is going on. This investigation is still ongoing but as part of that I noticed that sendEmulatorCommand may not always be doing the best it can to get the message through.
1 - each close in the finally block should be wrapped in its own exception handler to minimise the chance of leaked/unclosed streams.
2 - PrintWriter does not auto flush on writes. potentially print could be used but I just added flush.
3 - I have had bad experiences in the past of closing sockets on windows before the receiving process has processed the inflight data. The close seems to be able to overtake the data in the stream and appear as a closed exception before the inflight data is read. To minimize the risk of this I added a "quit" command after the desired command and then read the responses from the emulator until it gives end of stream.
In a few hours of testing I have not seen a failure to shutdown the emulator although I have seen a few situations where the emulator took a long time to respond to the sendEmulatorCommand requests.
The only concerns that I have over the changes that I have made are that the wait for the emulator command to quit could end up blocking the build if the emulator is really stuck. But then again in this instance the first call to readLine would likely stick anyway so I do not think it makes things any worse than before.
The above is available as patches at
I'll submit a pull request in due course.