You may be seeing this message and having the app crash when making API calls using something like Retrofit:
UnknownServiceException: CLEARTEXT communication to xxx.xxx.xxx.xxx not permitted by network security policy
This will only happen on newer devices as it’s a “feature” that was introduced in Android 9 (API level 28).
The cause is that you’re making a request using http
instead of https
(likely if you’re running the backend on your local machine for development purposes).
Generally, it’s not good practice communicating using http
in production, so the later versions of Android force you to use https
by default.
The solution is simple though, create a file named network_security_config.xml
in res/xml
(you might need to create the xml
directory too).
The contents of the new XML file should contain:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">http://xxx.xxx.xxx.xxx</domain>
</domain-config>
</network-security-config>
Where the xxx.xxx.xxx.xxx
part is your ip address or hostname that was shown in the initial exception message.
Then in your AndroidManifest.xml
file, add the lines:
<?xml version="1.0" encoding="utf-8"?>
<manifest>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:networkSecurityConfig="@xml/network_security_config"
>
</application>
</manifest>
This should only be used for development purposes, everything sent over http
instead of https
is visible to an attacker.