Using Golang + Gomobile To Build Android Application (with code)
Tags: go, android, webdev, javascript
Published: 2023-12-04 08:42:45

Thought of delving more in Go, after these articles: 
- [Using Golang to Build a Real-Time Notification System - A Step-by-Step Notification System Design Guide](https://dev.to/nikl/using-golang-to-build-a-real-time-notification-system-a-step-by-step-notification-system-design-guide-50l7)
- [JSON is Slower. Here Are Its 4 Faster Alternatives](https://dev.to/nikl/json-is-slower-here-are-its-4-faster-alternatives-2g30)

---

Whether your interest lies in developing a calculator or a notes application, this tutorial will help you in creating a simple Android application in Go.

Assuming our readers possess a foundational understanding of Go, we can delve directly into harnessing this robust language for mobile application development, specifically targeting the Android platform. 

## Tools in Deployment

To streamline the Android application development process, we will employ a suite of tools, each serving a specific purpose in our developmental journey.

1. **Go:**
   - A statically-typed, compiled programming language celebrated for its simplicity, efficiency, and robust support for concurrent programming.
   - Rapidly gaining traction in various projects, including mobile app development.

2. **Gomobile:**
   - A potent toolset facilitating the creation of mobile applications in Go.
   - Provides opportunities for crafting more efficient and resilient code, particularly when capitalizing on Go's speed and simplicity in a mobile context.

3. **Android SDK:**
   - Furnishes essential API libraries and developer tools required to construct, test, and debug Android applications.

4. **Go Modules:**
   - Introduced in Go 1.11, serving as the standard for dependency management in Go.
   - Offers enhanced version tracking and package distribution capabilities.

5. **Android Studio:**
   - The official Integrated Development Environment (IDE) for Android development.
   - Utilized for creating the user interface and implementing Java bindings generated by gomobile.

By adhering to this guide, you will gain a fundamental understanding of Go mobile development, acquiring practical skills that will prove beneficial in your journey as a mobile developer using Go and gomobile.

## Prerequisites

Before embarking on this endeavor, certain preparatory steps must be completed. Ensuring the correct setup for Go and gomobile and validating the Android SDK setup are critical prerequisites for a seamless Go mobile development experience.

### Verification of Correct Go and Gomobile Setup

1. **Ensure Go Installation:**
   - Execute the following command in a terminal:
     ```bash
     go version
     ```
   - Verify that the installed version of Go is displayed.

2. **Install Gomobile:**
   - Install using the following command:
     ```bash
     $ go install golang.org/x/mobile/cmd/gomobile@latest
     ```
   - Initialize gomobile with:
     ```bash
     gomobile init
     ```
   - Note: Initialization may take some time as it compiles the standard library for mobile platforms.

### Validation of Android SDK Setup

1. **Confirm Android Studio Installation:**
   - Ensure Android Studio is installed, including the necessary Android SDK.
   - Download from the official Android developer site if not already installed.

2. **Verify SDK Tools:**
   - Confirm that Android SDK Build-Tools, SDK Platform-Tools, and SDK Tools are up to date.
   - Navigate to the SDK Manager in Android Studio to check installed packages.
   - Verify the Android SDK location at the top of the SDK Manager.

By fulfilling these prerequisites, you can confidently proceed with Go mobile development, knowing that your tools are appropriately configured for building an Android application using Go and gomobile. In the following sections, we will delve into project setup, explore the gomobile toolset, and more. Stay tuned!

## Project Initialization

With our Go, gomobile, and Android SDK setups confirmed, it is time to initiate the construction of our Android application with Go. The initial step involves setting up the project, encompassing the creation of a new Go module and the establishment of a basic Go package.

### Creation of a New Go Module

In Go, modules represent collections of Go packages stored in a file tree with a go.mod file at its root. The go.mod file defines the module's module path, serving as its import path prefix, and outlines its dependency requirements.

To create a new Go module, navigate to your workspace and initiate a new module by executing:

```bash
go mod init <module-name>
```

Replace `<module-name>` with your desired module name. For example, if developing a calculator application, the module might be named "calculator." The command would then resemble:

```bash
go mod init calculator
```

This command generates a go.mod file in your project directory, serving as the repository for all dependencies as you progressively add them.

## Creating a Basic Go Package

Once our Go module is initialized, the next step in Go mobile development involves creating a basic Go package. In Go, a package is a collection of source files in the same directory that are compiled together.

1. **Create a New Package Directory:**
   - Generate a new directory for your package.
   - Create a new .go file, such as main.go.

2. **Example of a Basic Go Package:**
   ```go
   package main
   import "fmt"
   
   func Hello() string {
       return "Hello, World!"
   }
   
   func main() {
       fmt.Println(Hello())
   }
   ```
   - This code snippet illustrates a simple Go package with a Hello function returning a "Hello, World!" string.

By following these steps, you'll establish a Go module and a fundamental Go package as the starting point for your Android application using Go and gomobile. Subsequent sections will explore the gomobile toolset, initiating the construction of our Android application.

## Understanding the Gomobile Toolset

One of the critical aspects of building an Android application with Go is comprehending the gomobile toolset. As we progress with Go mobile development, gaining insights into the role of the gomobile toolset in Android app development and mastering gomobile bind becomes indispensable.

### Role of Gomobile in Android App Development

The gomobile toolset comprises powerful tools streamlining mobile application development using Go. It acts as a bridge between the Go programming language and the mobile environment, enabling developers to leverage Go’s simplicity and efficiency in Android applications.

An essential feature of gomobile is its ability to create mobile apps that call Go code through bindings. These bindings serve as a means to use Go functions in Android and iOS environments, extending Go's reach beyond the backend server-side development for which it is commonly known.

Furthermore, gomobile facilitates the generation of language bindings, enabling the Go package to be invoked from Java in Android. This capability is crucial, allowing developers to seamlessly incorporate Go’s performance and simplicity into their Android applications.

### Using Gomobile Bind

Among the various commands provided by the gomobile toolset, gomobile bind holds significant importance. This command is employed to generate language bindings for Go packages to be invoked in Java.

For instance, using the Hello function from the earlier section:

```go
package main
import "fmt"

func Hello() string {
    return "Hello, World!"
}
```

To generate Java bindings, navigate to the package directory and run:

```bash
gomobile bind -target=android
```

This command produces a .aar file, a binary distribution of an Android Library Project. The .aar file encompasses Java classes, manifest, and the compiled Go code as a native .so library. Integration into an Android Studio project allows invoking Go functions in Java.

Understanding the usage of gomobile bind is fundamental for Go mobile development and pivotal in building an Android application with Go and gomobile. As we proceed, we’ll discover how to integrate these Java bindings into our Android application, fully utilizing the Go package we've created.

# Building Your Simple Android Application

After gaining an understanding of the gomobile toolset, the development of our Android application with Go commences. This section covers the design of the application interface and the implementation of application logic in Go.

## Designing the Application Interface

Designing the application interface marks the initial step in bringing our Android application to life. For simplicity, this guide uses Android Studio’s layout editor to design the interface.

1. **Open Android Studio:**
   - Start a new Android Studio project, selecting Empty Activity as the template.
   - In the layout editor, drag and drop UI elements to design the interface.

2. **Customization:**
   - Customize properties of UI elements in the Attributes panel.
   - Assign IDs to each element for interaction in code.

3. **Example for a Calculator Application:**
   - For a calculator, use TextView for display and Buttons for digits and operations.

## Implementing the Application Logic in Go

With the interface designed, we delve into Go mobile development, implementing application logic in Go. Consider developing a simple calculator as an example.

1. **Defining Go Package for Calculator Logic:**
   ```go
   package calculator
   
   func Add(x, y float64) float64 {
       return x + y
   }
   
   func Subtract(x, y float64) float64 {
       return x - y
   }
   
   func Multiply(x, y float64) float64 {
       return x * y
   }
   
   func Divide(x, y float64) float64 {
       if y != 0 {
           return x / y
       }
       return 0
   }
   ```
   - Functions for addition, subtraction, multiplication, and division are defined in this package, handling potential division by zero error.

2. **Generate Java Bindings:**
   - Run `gomobile bind -target=android` to generate Java bindings for the Go package.

This phase blends creativity and logic, giving life to our simple Android application. In the upcoming sections, we'll integrate Go logic with our Android application, completing the final steps to bring our app to fruition.

# Integrating Go and Android

As we progress in building our Android application with Go, we've designed the interface and implemented the app logic in Go. The next step involves integrating Go code with our Android application, utilizing gomobile to generate Java bindings and incorporating Go functions into our Android code.

## Using Gomobile to Generate Java Bindings

As previously explained, gomobile bind is a crucial command generating Java bindings for our Go package. This process allows the direct invocation of Go functions in our Android Java code.

1. **Navigate to Package Directory:**
   - Run the following command:
     ```bash
     gomobile bind -target=android -o calculator.aar
     ```
   - This creates a calculator.aar file, including compiled Go code and Java bindings.

2. **Add to Android Studio Project:**
   - In Android Studio, go to File > New > New Module.
   - Choose Import .JAR/.AAR Package and locate the .aar file.
   - Finish the process to include your Go package in the Android Studio project.

Now, your Go package is part of your Android Studio project, ready to be utilized in your Android code.

# Using Go Functions in Your Android Application

## Integration of Go Functions

Now that the Go package is successfully added to our Android project, we can seamlessly incorporate Go functions into our Android application. Open the main activity file of your Android project and import your Go package:

```java
import calculator.*;
```

Subsequently, you can invoke Go functions just like any other Java function. For instance, in a calculator application, calling the Add function when the “+” button is pressed can be implemented as follows:

```java
Button addButton = findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Retrieve numbers from the input fields
        EditText firstNumber = findViewById(R.id.first_number);
        EditText secondNumber = findViewById(R.id.second_number);
        // Convert the numbers to double
        double x = Double.parseDouble(firstNumber.getText().toString());
        double y = Double.parseDouble(secondNumber.getText().toString());
        // Call the Add function from our Go package
        double result = Calculator.Add(x, y);
        // Display the result
        TextView resultTextView = findViewById(R.id.result);
        resultTextView.setText(String.valueOf(result));
    }
});
```

This section is pivotal in Go mobile development, facilitating the seamless integration of Go with Android. As you progress in building your Android application using Go and gomobile, the power of Go proves to be a valuable asset. In the subsequent section, we will delve into testing and debugging, concluding the application for its grand debut!

# Building and Testing Your Application

## Final Steps in Development

With the integration of our Go code into our Android application, we are approaching the final stages of building an Android application with Go. The subsequent steps involve building and testing the application to ensure its performance and correctness.

## Building Your Android Application

Building your Android application in Android Studio is a straightforward process. Navigate to Build > Make Project or use the keyboard shortcut Ctrl+F9.

This action compiles your code and generates an APK (Android Package Kit) suitable for installation on an Android device. The Build window at the bottom of the Android Studio interface will display the build output. A successful build will be indicated by a BUILD SUCCESSFUL message.

For app distribution, consider generating a signed APK or a signed app bundle. Proceed to Build > Generate Signed Bundle / APK... and follow the prompts.

## Running and Testing Your Application

Running your Android application can be done on a physical Android device or an emulator. Click on the green arrow in the toolbar or navigate to Run > Run 'app'.

If a physical Android device is connected to your computer with USB debugging enabled, it will appear in the Select Deployment Target window. Alternatively, create a new virtual device by selecting Create New Virtual Device... and following the prompts.

Thoroughly test your application, ensuring all functionalities and edge cases are covered. In the case of a calculator app, test various operations with different numbers, including edge cases like division by zero.

Testing is integral to Go mobile development. Dedicate time to comprehensive testing to ensure a smooth and enjoyable user experience.

Congratulations! You've successfully built an Android application using Go and gomobile. Armed with these skills and tools, you are now prepared to take on more ambitious projects and bring your innovative ideas to life.

## Conclusion

Our journey in building an Android application with Go and gomobile has been substantial. Let's recap the achievements and look forward to what lies ahead in Go mobile development.

1. **Setup of Go and Gomobile:**
   - Ensured the correct setup of Go and gomobile, foundational tools for Android application development with Go.

2. **Creation of Go Module and Package:**
   - Initiated a new Go module and built a basic Go package, leveraging Go's simplicity and efficiency in mobile app development.

3. **Understanding Gomobile Toolset:**
   - Explored the role of the gomobile toolset in Android app development, mastering the use of gomobile bind for generating language bindings.

4. **Android App Development:**
   - Designed the app interface and implemented application logic using Go, marking a critical integration point of Go and Android.

5. **Building, Running, and Testing:**
   - Successfully built and tested the Android application, ensuring its functionality and performance.

---

> #### Similar to this, I run a developer-centric community on Slack. Where we discuss these kinds of topics, implementations, integrations, some truth bombs, lunatic chats, virtual meets, and everything that will help a developer remain sane ;) Afterall, too much knowledge can be dangerous too.

> #### I'm inviting you to join our free community, take part in discussions, and share your freaking experience & expertise. You can fill out this form, and a Slack invite will ring your email in a few days. We have amazing folks from some of the great companies (Atlassian, Gong, Scaler etc), and you wouldn't wanna miss interacting with them. [Invite Form](https://forms.gle/VzA3ST8tCFrxt39U9)