Wednesday, November 6, 2013

Simulate a cellular network over Wi-Fi using Android's emulator

Check out scripts William J. Francis uses on his standard Android emulator when emulating cell networks during testing.

While it would be wonderful for developers and users if everywhere we went our cell phones were connected to screaming fast Wi-Fi, the reality is quite different. There are times we are lucky to have 3G or even EDGE (shudder) connectivity. As responsible Android developers, it is our obligation to ensure the applications we create behave at least reasonably well under these conditions.
So what can you do to simulate slow or spotty cellular coverage? Believe it or not, I read one forum thread where a developer claims the best solution is to load your app onto your phone and then place it inside of any microwave oven! No, thanks. While I'm all for thorough testing, I'm not sure my Nexus 4 is microwave safe.

Fortunately, the Android emulator that ships as part of the SDK has some baked-in features to assist you with this kind of testing -- and the best part is you don't have to nuke your $300 smartphone. You won't find these sort of advanced options in the Android Virtual Device (AVD) GUI, but you can invoke them by connecting a command console to an already running instance. On my MacBook from a bash shell, I can connect to an AVD like this:

telnet localhost 5554
Once connected, the following commands will simulate a 3G connection:

network delay umts
network speed umts
You can verify the settings took by entering:

network status
If everything is working, you'll get a network dump that looks something like this:

Current network status:
  download speed:    1920000 bits/s (234.4 KB/s)
  upload speed:       128000 bits/s (15.6 KB/s)
  minimum latency:  35 ms
  maximum latency:  200 ms
The above settings are those I most frequently use when testing how my application behaves on initialization and how well my caching schema works. However, the emulator allows even a finer grain of control if you need to verify more hostile network conditions. Read the official documentation for a rundown of all the available options.