CLEARTEXT communication not permitted by network security policy

How to deal with the UnknownServiceException: CLEARTEXT communication not permitted error.

January 28, 2021 - 2 minute read -
Android Tutorial Kotlin

You may be seeing this message and having the app crash when making API calls using something like Retrofit:

UnknownServiceException: CLEARTEXT communication to 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"?>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true"></domain>

Where the 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"?>
    <uses-permission android:name="android.permission.INTERNET" />

This should only be used for development purposes, everything sent over http instead of https is visible to an attacker.