0

I'd like to cut off emulator's internet while keeping wifi and mobile data enabled so I can run some automated tests covering this case without having to turn off the internet manually.

While running an emulator on the PC it gets its internet access through the host PC, I'm interested in whether there's an adb command that would let me disable (and re-enable mid-test, potentially multiple times) the internet access the emulator is getting from the host PC while keeping wifi and mobile data enabled?

I've been using svc wifi/data enable/disable to enable and disable wifi and mobile data repectively.

This could be a duplicate of Can I truly enable and disable network access mid-test? but taking into account that it's almost 10 years old something might have changed in the meantime.

J.Grbo
  • 435
  • 5
  • 11
  • Not sure about the Android Emulator for Android SDK, but other emulators that base on VirtualBox (like Genymotion) you can cut of network from the emulator at run-time by disabling the virtual network adapter of the emulator. – Robert Jul 13 '22 at 09:39

2 Answers2

1

As loss of internet connectivity is a completely external event, the most accurate way you can simulate it is using a proxy.

First, configure a proxy in your network. You can even write one in a few lines of python if you want to have more control over it.

Then start the emulator providing the command line option -http-proxy or the environment variable http_proxy defining your proxy. This option forces the emulator to use the specified HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not currently supported.

For example

emulator -http-proxy http://192.168.200.1:9999

then, you can control the emulator access to the internet (HTTP/HTTPS) via the proxy.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0

Diego's answer pushed me in the right direction.

Using: add shell settings put global http_proxy <ip>:<port> and add shell settings put global http_proxy :0 to set and reset emulator's global proxy along with using the same proxy in the code (if it's set, to check so I'm using System.getProperty("http.proxyHost") and System.getProperty("http.proxyPort")), because it's not used automatically, I was able to achieve what I wanted.

Thanks Diego.

Edit: In fact the APIs such as HttpURLConnection do use the proxy automatically (if set, so no checking and manually setting needed on my side). Well HttpURLConnection comes with its own problems such as not always honouring timeouts, so back to using other APIs and manually checking for proxy and if set using it.

J.Grbo
  • 435
  • 5
  • 11