Engineering

How to Use Python, Flask, and Termux to Build a Simple Android App

Gidraf Orenja
By Gidraf Orenja
  • Blog
  • Engineering
  • How to Use Python, Flask, and Termux to Build a Simple Android App

In the first article in this two-part series, I wrote about how you can code the very simplest structure of the web app server on an Android device. Now, we are going to move one step further and actually build a web-based application that will run on an Android phone. The app that this tutorial will walk you through is a simple text-to-speech application built on a simple Flask server. The app will accept speech, convert it into text, and the UI is a simple input form that includes a button to send the text to the server.

In order to build the app, you need at least some basic knowledge of the Termux Android terminal emulator and Python language because I will not discuss those programs in this tutorial.

Because we will be working on your phone, make sure that you have Termux and Python preloaded. If you don’t know how to install each of these on your mobile device, check out my previous post.

The text editor we will be using to edit our Python file is Vim. To make sure you have access to Vim, open Termux and run pkg install vim on your terminal.

Run pkg install termux-api once Vim is done installing so that the Termux API package installs. We will use termux-tts-speak, part of the Termux API package, in our work today. If you aren’t knowledgeable on these available API packages, read more about it here.

Run python3 -m venv text-to-speech to make a virtual environment.

Next, activate the virtual environment we just created by running source text-to-speech/bin/activate.

To add or install the Flask virtual environment run pip install flask.

Once Flask has completed the installation process run touch run.py to create a run.py file. If you ls at this point you should now be able to see a new run.py file.

You can just clone the repo using Git. Git is installed the same way as vim, just run pkg install git.

After Git has installed clone the repo by running this Git clone.

Next, open the file you have just created by running vim run.py. The code we will use to convert text to speech using the Termux-API and an Android text-to-speech engine will be written here.

Copy and paste the following code into your Vim editor by tapping the letter i on the keyboard and changing the mode of the editor to edit/insert.

import subprocess
from flask import Flask,request, render_template
app = Flask(__name__)
@app.route('/',methods=["GET","POST"])
def playsound():
    if request.method == 'GET':
        return '''<!DOCTYPE html>                                       <html>                                                        <link rel="stylesheet" href="static/style.css">                                                     <body>                                                                                                                                                            <form action="/" method="POST" style="border:1px
solid #ccc">                                            <div class="container">                                 <h1>Play sound</h1>                                        <hr>                                                                                                        <input id="text" type="text" placeholder="Text to play" name="text" required>                                                                                     <button type="submit" class="signupbtn">Play</button>                                                       </div>                                              </div>                                              </form>                                               
</body>'''
    text = request.values.get("text")
    MyOut = subprocess.call(f'''termux-tts-speak {text}''', shell=True)
    return '''<!DOCTYPE html>                                       <html>                                                        <link rel="stylesheet" href="static/style.css">                                                     <body>                                                                                                                                                            <form action="/" method="POST" style="border:1px
solid #ccc">                                            <div class="container">                                 <h1>Play sound</h1>                                        <hr>                                                                                                        <input id="text" type="text" placeholder="Text to play" name="text" required>                                                                                     <button type="submit" class="signupbtn">Play</button>                                                       </div>                                              </div>                                              </form>                                               
</body>'''
if __name__ =='__main__':
    app.run(debug=True)

Let me explain the code above:

The Flask and subprocess modules are imported. The Flask package is used to allow the server to communicate with the browser and the subprocess runs the terminal command within Termux. Another part of the above code initializes the Flask class and routes to home ‘/’. There are two route methods included, GET and POST. The code includes a check on if the method is GET, and if it is the program returns the HTML string. If the method is POST the app begins processing the text-to speech logic and returning the HTML string. This is one of the simplest ways the Flask server app can be used, but there are many more. If you would like more information on ways Flask can be utilized, read more about it here.

Paste the code above the Vim text editor.

Once done tap ESC button on top of your keyboard

Run python run.py to start the Flask server.

Once all the steps are complete you can navigate to your browser on URL localhost:5000. You should see an edit text field and a button. To test the app capability we just coded, type anything into the box and hit the play button. You should be able to hear the results of your coding when your Android reads your text. It may take a moment for the server to respond, but be patient, the Android text-to-speech engine needs to be activated.

Congratulations, you have just build a functional web app on your phone. Thanks for reading!

Are you a Python developer looking for your next role? Apply to join the Andela Talent Network today.

Gidraf Orenja
Written by
Gidraf Orenja
A passionate self-taught developer, Gidraf Orenja is a full-stack engineer who sharpened his technical skills with Andela training programs. He is based in Nairobi, Kenya.