April 20, 2017

Updating hosts file on Android Emulator

To update the hosts file on an Android Emulator, follow these steps:

  1. Start a command prompt window and switch to Android SDK's tools folder:
    C:\>cd %LOCALAPPDATA%\Android\sdk\tools
    
  2. Use the emulator tool to find the name of the AVD you want to start. (Note that in AVD Manager GUI tool, the names listed here are the AVD IDs, basically spaces replaced with underlines.)
    C:\Users\user\AppData\Local\Android\sdk\tools>emulator -list-avds
    Pixel_API_25
    
  3. Start the emulator with writable system image option turned on:
    C:\Users\user\AppData\Local\Android\sdk\tools>emulator -avd Pixel_API_25 -writable-system
    

    Wait for the emulator to boot up. The documentation says -writable-system option creates a temporary copy of the system image that will be destroyed when the emulator exists, but the hosts file change seems to survive shutdowns.

  4. Start another command prompt window, and switch to Android SDK's platform-tools folder:
    C:\>cd %LOCALAPPDATA%\Android\sdk\platform-tools
    
  5. Use the adb (Android Debug Bridge) tool to remount:
    C:\Users\user\AppData\Local\Android\sdk\platform-tools>adb root
    
    C:\Users\user\AppData\Local\Android\sdk\platform-tools>adb remount
    remount succeeded
    

    This will remount system/ as read/write.

  6. Now use the adb to start a remote interactive shell and run the following commands to update the hosts file:
    C:\Users\user\AppData\Local\Android\sdk\platform-tools>adb shell
    generic_x86:/ # cd /system/etc
    generic_x86:/system/etc # echo "192.168.1.1 dev.site.com" >> hosts
    

    Make a backup first if needed, and use cat hosts to verify that hosts file has been updated.

Now start Chrome in the emulator and browse to http://dev.site.com and it should work.

Googling on this topic also mentions using adb push/pull commands to copy the hosts file, but it didn't seem to work at first, at least with Android Studio 2.3.1/API Level 25. The hosts file copies successfully, but Chrome gives DNS error. However, subsequent tries worked after creating a new hosts file and copying it over, instead of pulling the existing hosts file and editing it then pushing it. Not sure what the cause was, my initial guess was the ordering of IP4 and IP6 addresses in the hosts file, but confirmed that's not the case...the file was LF endings, too.

Reference: http://www.bradcurtis.com/hosts-files-and-the-google-android-emulator/

No comments:

Post a Comment