Running Go on Android

January 15, 2017

Running indirectly…

The Go Mobile project is marked as “experimental” and I guess it will take a couple of years until we’ll get some stable version. The way I’m going to show you how to run Go programs on Android is a bit tricky as it actually uses Termux which is an Android terminal emulator and Linux environment app. Technically we could install and run there many other languages, but let’s see how it’s getting on with Go. What makes Termux really interesting is the API we can use to access the Android API. For instance we can check our battery status, take a photo or check our device GPS location. Before we continue, install these two apps on your Android phone:

  • Termux
  • Termux API

That’s what I see when typed uname -a

Installing Go on Termux is as easy as firing up apt install golang

It takes 216 MB of additional disk space. The process shows exactly what packages are downloaded and installed. You can see the deb format is used.

Let’s type go version

Nice! isn’t? :) go is installed in:

    $ which go
    /data/data/com.termux/filex/usr/bin/go

Having vi we can type our program directly at the console ;) ..give it a try and in the meantime I will download an example using …curl (we’ll use go get later on) Type apt install curl and once it’s installed, run this:

    $ curl https://raw.githubusercontent.com/adonovan/gopl.io/master/ch8/spinner/main.go > main.go

This is an example from “The Go programming Language” book by Alan A. A. Donovan & Brian W. Kernighan.. The code computes the 45th Fibonnaci number. Saving the curl result into main.go file:

and running it go run main.go works!

what about compiling? go build main.go

works!

If you used go before you know that go supports downloading dependencies/packages by running go get. Firstly we need to set up $GOPATH.

    $ echo $HOME
    /data/data/com.termux/files/home
    $ mkdir $HOME/mygo
    $ export GOPATH=$HOME/mygo
    $ echo $GOPATH
    /data/data/com.termux/files/home/mygo

(it’s worth to save GOPATH in your .bashrc)

and install git by running:

    $ apt install git

Now, run let’s test go get by downloading a popular Go toolkit gorilla:

    $ go get github.com/gorilla/mux

tree mygo shows:

Termux API

So far, so good. The power of Termux lies in the API. Get familiar with the available API here.

For instance, run termux-battery-status

The API’s result is returned as JSON! This is absolutely brilliant!

If you want to upload and run your own Go programs under Termux you should find a way to get your code there.

Run this command to access storage folders on your mobile phone:

    $ termux-setup-storage

Grand permissions to acccess folders.

Now run ls to see available folders. You should see more folders available. You can use usb to access files on your phone but I won’t describe it here (you know how to do it, don’t you? ;) )

Ok, let’s build a go program that is returning the current status of the phone’s battery:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "os/exec"
)

var Battery struct {
    Health      string
    Percentage  int
    Status      string
    Temperature float64
}

func main() {
    cmd := exec.Command("termux-battery-status")

    //StdoutPipe returns a pipe that will be connected to
    //the command's standard output when the command starts
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }
    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }

    if err := json.NewDecoder(stdout).Decode(&Battery); err != nil {
        log.Fatal(err)
    }

    //Wait waits for the command to exit
    //It must have been started by Start
    if err := cmd.Wait(); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The battery is %s and is charged in %d percentage\n",
        Battery.Health, Battery.Percentage)
}

…and running it shows:

I put the code to GitHub, so you can curl it from there :) : https://github.com/rafalgolarz/termux-go

How about displaying the result in a Toast (a transient popup)?

More ideas

The API allows sending SMS’, taking photos, speak text with a system text-to-speech (TTS) engine, and much more. I can imagine a background process ($ ./yourgoprogram &) that takes pictures periodically and sends them to a contact of your list. This would act as a security camera. I hoped you liked it, I think Termux is a perfect bridge between languages that cannot compile to native Android app and developers who want to access their devices’ API.