Skip to content

Instantly share code, notes, and snippets.

@fdelbos
Last active July 19, 2024 00:41
Show Gist options
  • Save fdelbos/9f480b76e1debad656af33cb297adecf to your computer and use it in GitHub Desktop.
Save fdelbos/9f480b76e1debad656af33cb297adecf to your computer and use it in GitHub Desktop.
Build and install a go library for android studio

Build and install a go library for android studio

Setup

brew tap homebrew/cask-versions
brew install --cask temurin11

Create a go package

mkdir demo
cd demo
go mod init github.com/fdelbos/demo

Import in Android Studio

In this package create a demo.go file with the following:

package demo

type (
	Demo interface {
		Hello(string) string
	}

	srv struct{}
)

func NewDemo() Demo {
	return &srv{}
}

func (s *srv) Hello(name string) string {
	return "Hello " + name
}

Build a jar

  • get the mobile tooling: go get golang.org/x/mobile/bind
  • build:
mkdir -p build && \
gomobile bind \
  -o build/demo.aar \
  -target=android \
  -androidapi 30 \
  github.com/fdelbos/demo

You should get the following:

ls -lah build/
total 5
drwxr-xr-x  4 fred  staff   128B Apr 20 12:39 .
drwxr-xr-x  6 fred  staff   192B Apr 20 12:39 ..
-rw-r--r--  1 fred  staff   5.7K Apr 20 12:39 demo-sources.jar
-rw-r--r--  1 fred  staff   4.8M Apr 20 12:39 demo.aar

Import in Android Studio

  • Add the dependency in the ** app / libs ** folder

Screenshot 2023-04-20 at 13 10 42

  • In an existing project, click on: File > Project Structure > Dependencies

Screenshot 2023-04-20 at 12 55 52

  • set the AAR path

Screenshot 2023-04-20 at 13 11 31

  • In Graddle you should have a new line for your dependency:

Screenshot 2023-04-20 at 13 14 50

Enjoy

  • Now you can update your code to use the new library:

Screenshot 2023-04-20 at 13 15 43

  • Check on the emulator

Screenshot 2023-04-20 at 13 16 32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment