title: How do I make sure ports 8200..8299 for UIAutmator2 are free'd up after killing Appium?
body: <p>I'm running Appium 24/7 on a Windows machine to perform automated tests. I'm running these tests via AVD on an emulator with Android 10. For my test, I give the correct Capabilities and runs functionally great. But after a few hours/days I get the follow error:</p>
  <p><code>UnknownError: An unknown server-side error occurred while processing the command. Original error:*Cannot find any free port in range 8200..8299}. Please set the available port number by providing the systemPort capability or double check the processes that are locking ports within this range and terminate these which are not needed anymore at getResponseForW3CError at asyncHandler.</code></p>
  <p>When my code is executed, I make sure the <code>finally</code> in <code>try</code> executes the <code>AppiumDriverLocalService.stop();</code> method to kill Appium. My feeling says this does somehow not free up any ports for UIAutomator2 (which you can configure, but I have not configured, through <code>systemPort</code> capability.</p>
  <pre><code>    } finally {
          driver.closeApp();
          service.stopServer();
          System.exit(0);
      }
  </code></pre>
  <p>Why does Appium not free up any ports for UIAutomator2 in the range 8000-8299 after stopping the service?</p>
  <ul>
  <li>Android Debug Bridge version 1.0.40</li>
  <li>Appium version 1.20.2</li>
  <li>Android 10</li>
  </ul>
  <p><em>PS I know of the adb command <code>adb -s $UDID forward --remove-all</code> but does this solve the real issue, I don't want to execute a Java Process each time</em></p>
  <p><strong>Update - Fix 2-3</strong></p>
  <p>I have fixed the issue by changing the <code>finally</code> clause to execute the following methods in order:</p>
  <pre><code>    } finally {
          AndroidDriver.quit();
          AppiumDriverLocalService.stopServer();
  </code></pre>
  <p>In order to free up the port 8200..8299, AndroidDriver must be quit as UIAutomator2 is linked to this. The AppiumDriverLocalService will kill/forward/free this port and UIAutomator2, after this I can freely stop the server:</p>
  <p><code>[ADB] Removing forwarded port socket connection: 8203</code></p>