Easy Code Share > Cordova > Solving Cordova Android 9 Clear Text Not Permitted

Solving Cordova Android 9 Clear Text Not Permitted


This issue might happen when you build an Cordova APP on Android 9, but can’t send messages to non-SSL websites. This article discusses about why the limit exists, how to permit clear text, and what correct process we should do.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 7 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
 DOWNLOAD SOURCE

 

SECTION 1
Android 9.0 Declare Security

Android 9 release announced a significant default on HTTP clear text. The default setting is FALSE. That means you have to move websites to be HTTPS, or find tips to change the default.

 

HTTP Clear Text Not Permitted

This blog has written posts about Cordova AJAX and relevant topics. Here is another issue that you could encounter in developing. Since August 6, 2018 that is the time Android 9 released on, you might have built an APP tested on a newly purchased Android phone, but failed to make HTTP requests. However, it worked on old-version Android phones.

Such a trouble caused by platform version does waste your time. Because Android 9 decides to march toward a world in which all websites must use HTTPS, the default settings does not allow clear text requests. Can we fix it? There are potential ways to fix it as below.

 

Methods to Deal With Android 9.0 Limit

Alternative treatments are

  • Move HTTP to HTTPS: You can get free or paid solutions to add SSLs to websites. We have provided a free solutions previously.
  • Change Settings in Android APP: No matter you are building native or hybrid APPs, The changes to accept clear text will be available.

In next section, we demonstrate the latter approach by an example in building a Cordova hybrid APP.

 

SECTION 2
Reduce Android 9.0 Security

For some APPS in which data are not so important, you would allow clear text messages to send. This section show you how to change settings on Android 9 by using a Cordova project for guessing number.

 

Re-Configure to Allow Clear Text

In case that some websites don’t want to become of HTTPS, the APPs connected to these websites should accept HTTP instead. To make APPs do it, we have to modify and add more Android files as the following steps.


STEP 1:

In Cordova projects, modify Android file AndroidManifest.xml located in the folder of cordova-project/platforms/android/app/src/main by adding these 2 options as below in its <application> tag.

android:networkSecurityConfig="@xml/network_security_config"

android:usesCleartextTraffic="true"

Therefore, <application> tag becomes

<application android:hardwareAccelerated="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:usesCleartextTraffic="true">


STEP 2:

In cordova-project/platforms/android/app/src/main/res/xml folder, add a new Android file network_security_config.xml, which contains

<?xml version='1.0' encoding='utf-8'?>
  <network-security-config>
    <base-config cleartextTrafficPermitted="true" />
  </network-security-config>


STEP 3:

Finally, in the file AndroidManifest.xml, you can add the following content as a bottom line in the tag <application> for http clear text.

<uses-library android:name="org.apache.http.legacy" android:required="false" />


These 3 steps will lead to the change of accepting clear text. We use a guess number game to demonstrate it.

 

Guess Number Example

Suppose that a non-SSL website has a random number to be guessed, a Cordova guess game APP on Android 9 sends a number to try and gets answers of “It’s Bigger” or “It’s Smaller” for direction decision in next tries. Keep trying several times till getting final anwser of “Congratuations …”

Cordova Guess Game in Android 9

HTML files use tag attributes provided by jQuery Mobile, thus resulting layout fit mobile phones from the view of responsive design.

index.html
<div data-role="page" style="background:blue;">
    <div data-role="header">
        <h1>GUESS NUMBER</h1>
    </div>
    <div data-role="content">
        <div class="user-data">
        <p>Guess a number between 1 and 100.</p>
        <input type="number" data-clear-btn="true" id="number">
        <button class="ui-btn ui-corner-all" id="tryit">GUESS</button>
        <p id="answer"></p>
        </div>
    </div>
    <div data-role="footer" data-position="fixed">
        <p style="text-align:center;">Cordova Android 9 Clear Text Test</p>
    </div>
</div>
.....
<script>
//var data = {};
$(document).ready(function() {
    $('#tryit').on("click", function() {
        sendout($("#number").val());
    });
});
</script>

Each time AJAX requests use GET method to send a guessed number to try. Responses give a clue to users for next try.

index.js
var url_test = "http://www.example.com/ajax-server.php";
function sendout(d) {
    console.log(d);
    $.get( url_test,
        { guess:d },
        function(r) {
            console.log("recv:"+r);
            $("#answer").text(r);
        }
    );
}

Remember to include cross-domain header in AJAX server to avoid CORS. It could be header("Access-Control-Allow-Origin:*").

ajax-server.php
<?php
header("Access-Control-Allow-Origin:*");
$guess = $_GET["guess"];
$fname = dirname(__FILE__) . "/random.txt";
if(!file_exists($fname)) file_put_contents( $fname, rand(1,100) );
if($guess > file_get_contents($fname))
    echo "It's bigger!";
elseif($guess < file_get_contents($fname))
    echo "It's Smaller!";
else {
    unlink($fname);
    echo "Congratulations, " . $guess . " is right.";
}
?>

Once guessed correctly, the file containing a random number in server sites will be deleted.

 

SECTION 3
Build Cordova Project

Apart from normal Cordova building process, we emphasize the changes to the Android 9 default settings with given template files.

 

Cordova Create Project

c:\>cordova create guessgame com.easycodeshare.guessgame GuessGame
Creating a new cordova project.

For example, Cordova CLI command line generates guessgame folder. Replace all files in guessgame/www folder with downloaded example files. Refer to procedure of building Cordova APPs for more details.

Cordova Project Files on Android 9

 

Cordova Add Platform of Android 9

First, choose a platform to build APPs or optionally list installed platforms.

c:\guessgame>cordova platform add android
Using cordova-fetch for cordova-android@^9.0.0
Adding android project...
Creating Cordova project for the Android platform:
        Path: platforms\android
        Package: com.easycodeshare.guessgame
        Name: GuessGame
        Activity: MainActivity
        Android target: android-29
Subproject Path: CordovaLib
Subproject Path: app
Android project created with cordova-android@9.0.0
Discovered plugin "cordova-plugin-whitelist". Adding it to the project
Installing "cordova-plugin-whitelist" for android
Adding cordova-plugin-whitelist to package.json
c:\guessgame>cordova platforms
Installed platforms:
  android 9.0.0
Available platforms:
  browser ^6.0.0
  electron ^1.0.0
  windows ^7.0.0

 

Modify The Android Manifest File

Every APP project must have an AndroidManifest.xml file. The manifest file describes essential information about your APP to the Android system and Google Play. The contents to modify for clear text permission are in Section 2.

The guessgame/for-clear-text folder contains 2 template files you can use for permitting clear text. Just put them into proper locations as discussed before.

Clear Text Permission Template Files

 

Change to Real URL for Testing

Move ajax-server.php mentioned above to your website, and change guessgame/www/js/index.js to direct to correct HTTP URL such as

var url_test=http://www.example.com/ajax-server.php.

 

Build Cordova APPs

c:\guessgame>cordova build android
Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting)
ANDROID_HOME=undefined (DEPRECATED)
Using Android SDK: C:\Users\user\AppData\Local\Android\sdk
Starting a Gradle Daemon (subsequent builds will be faster)
BUILD SUCCESSFUL in 26s
1 actionable task: 1 executed
Subproject Path: CordovaLib
Subproject Path: app
Starting a Gradle Daemon (subsequent builds will be faster)
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 42s
40 actionable tasks: 40 executed
Built the following apk(s):
        c:\guessgame\platforms\android\app\build\outputs\apk\debug\app-debug.apk

 

FINAL
Conclusion

Android 9 pay more attentions to HTTP security than before. Probably one day all transmission should be under SSL protection. Fortunately, there are free HTTPS approach to be used.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Learning Tips

Let us suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.

 

Suggested Reading

 

TRY IT
Quick Experience

That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.

 

Try It Yourself

Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.

Leave a Comment