Edit Android’s emulator hosts file
Recently, I’ve developed Android app that during the development requires access to the backend service that is run in the docker behind reverse-proxy with custom myservice.traefik.me
domain name.
For sure, from emulator you can get access to your local service when connect to it by IP address with specified port. But this approach leads to some issues and ugly workarounds in a code.
There are several solutions to this problem like edit hosts file, run own DNS server etc. But the simplest one is just simply editing hosts file on emulator.
Solution
By default the file system is read-only. So to be able to edit hosts file we need to start emulator from command line with -writable-system
argument.
Open terminal and navigate to the tools folder \android-sdk\tools
or \android-sdk\emulator
, by default on windows Android SDK installed to c:\Program Files (x86)\Android\
.
Run the following command to get list of the installed virtual devices
emulator -list-avds
# pixel_5_-_api_30
Next, let’s start emulator with writable file system
emulator -avd pixel_5_-_api_30 -partition-size 512 -writable-system
Now, when emulator has been started, we need to reconnect and remount ADB tool. Open new terminal window and navigate to the \android-sdk\platform-tools
folder. On windows Android SDK installed to c:\Program Files (x86)\Android
folder.
Restart ADB. This step is optional, but maybe required if following commands are failing.
adb reboot
Wait until emulator has been restarted, then
adb root
Next, get list of the available devices
adb devices
#emulator-5554
And finally let’s remount selected device
adb -s emulator-5554 remount
Now we are ready to edit hosts
file. Download it to a local folder. In this example to the current folder.
adb -s emulator-5554 pull /system/etc/hosts hosts
Get the host machine IP address
ipconfig # on Windows
ifconfig # on Mac OS
ip addr # on Linux
Edit hosts
file like this.
Note: enter your IP and service name.
192.168.0.13 myservice1.traefik.me
192.168.0.13 myservice2.traefik.me
Upload hosts
file back to the emulator
adb -s emulator-5554 push hosts /system/etc/hosts
Done. Now you can access your local resources from you app using custom domain names.
NOTE: If you have more than one service and you do not use reverse proxy, you will most likely need to specify a port number e.g.
https://myservice1.traefik.me:8080
.