Accessing localhost:port from Android emulator
You can access your host machine with the IP address "10.0.2.2
".
This has been designed in this way by the Android team. So your webserver can perfectly run at localhost and from your Android app you can access it via "http://10.0.2.2:<hostport>
".
If your emulator must access the internet through a proxy server, you can configure a custom HTTP proxy from the emulator's Extended controls screen. With the emulator open, click More , and then click Settings and Proxy. From here, you can define your own HTTP proxy settings.
Since 10.0.2.2
is not a secure domain for Android you have to allow non-secured domains in your network configuration for API 28+ where non-TLS connections are prevented by default.
You may use my following configurations:
Create a new file in main/res/xml/network_security_config.xml as:
<?xml version="1.0" encoding="utf-8"?><network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">localhost</domain> <domain includeSubdomains="true">10.0.2.2</domain> </domain-config></network-security-config>
And point it in AndroidManifest.xml
<application............android:networkSecurityConfig="@xml/network_security_config">