Golang for Android Development
It’s good to write Golang for producing binary file, then use it everywhere
Cython
could do the same thing by convert python to c, then c to binary.
First, you should write a program at ~/go/github/yingshaoxo/hi/main.go
package greeting
func SayHi() string {
return "Hi!"
}
Capitalize the function name, so golang would treat that function as public.
Then, compile it to a binary file
go get golang.org/x/mobile/cmd/gomobile
gomobile init
gomobile bind -target=android
If it ask for NDK, install it and make sure the Environmental-Variable was set right.
#add the following to your `~/.bashrc`:
export ANDROID_HOME=$HOME/Android/Sdk
export ANDROID_NDK_HOME=$ANDROID_HOME/ndk/21.3.6528147
export PATH=$PATH:$GOPATH/bin:$ANDROID_HOME/platform-tools/
If everything was right, you’ll get two files: greeting.aar
and greeting-sources.jar
Let’s import it to Android Studio Project
Let’s assume you have a project which was named
ABI_Test
mkdir ABI_Test/app/libs
mv greeting.aar ABI_Test/app/libs/
andmv greeting-sources.jar ABI_Test/app/libs/
add
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
toABI_Test/app/build.gradle
rebuild the project
Let’s use it with the following codes
import greeting.Greeting
var words = Greeting.sayHi()
Toast.makeText(applicationContext, words, Toast.LENGTH_LONG).show()
The real codes
import greeting.Greeting
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var words = Greeting.sayHi()
Toast.makeText(applicationContext, words, Toast.LENGTH_LONG).show()
}
}
https://github.com/yingshaoxo/Go_tutorial_for_Pythoner/blob/master/go-for-android.md