Fix Cleartext Traffic Error in Android 9 Pie

Fix Cleartext Traffic Error in Android 9 Pie

Image for post

Finally, Android Pie was released and we can?t wait to try it on an existing project. But when we try to run our app on emulator, we saw this error Cleartext HTTP traffic to * not permitted

So what this exactly mean?

Cleartext is any transmitted or stored information that is not encrypted or meant to be encrypted.

When an app communicates with servers using a cleartext network traffic, such as HTTP, it could raise a risk of eavesdropping and tampering of content. Third parties can inject unauthorized data or leak information about the users. That is why developers are encouraged to a secure traffic only, such as HTTPS.

But just in case using cleartext is inevitable, developers can fix the error by

  1. Editing useCleartextTraffic attribute in manifest file, or
  2. Adding Network Security Config

Android 6.0 introduced the useCleartextTraffic attribute under application element in android manifest. The default value in Android P is ?false?. Setting this to true indicates that the app intends to use clear network traffic.

<application android:usesCleartextTraffic=”true”

However, this may appear to fix the problem but it opens a threat to data integrity. A better solution is offered in Android 7.0 through network security configuration file.

Network security configuration allows an app to permit cleartext traffic from a certain domain.

How to use it?

  1. Add a network security config file under res/xml.

Image for postadded res/xml/network_security_config.xml

2. Add a domain config and set cleartextTrafficPermitted to ?true?.

<?xml version=”1.0″ encoding=”utf-8″?><network-security-config> <domain-config cleartextTrafficPermitted=”true”> <domain includeSubdomains=”true”></domain> </domain-config></network-security-config>

3. Add your network security config to your Android manifest file under application.

<application android:name=”.MyApplication” android:networkSecurityConfig=”@xml/network_security_config”…

TL;DR ? You can fix cleartext traffic error by adding useCleartextTraffic=?true? in android manifest or by adding your domain through a Network security config file and set cleartextTrafficPermitted=?true?.

But still at the end of the day, better use a secure network traffic rather than a cleartext.


No Responses

Write a response