要實(shí)現(xiàn)Android原生功能調(diào)用,可以使用GoMobile工具來(lái)創(chuàng)建一個(gè)Android庫(kù),并在Go代碼中調(diào)用該庫(kù)中的函數(shù)。以下是實(shí)現(xiàn)的步驟:
gomobile init -ndk /path/to/android/sdk/ndk-bundle
package main
import (
"fmt"
"gomobile.org/x/mobile/app"
"gomobile.org/x/mobile/event/lifecycle"
"gomobile.org/x/mobile/event/paint"
"gomobile.org/x/mobile/event/touch"
"gomobile.org/x/mobile/gl"
)
func main() {
app.Main(func(a app.App) {
var glctx gl.Context
for {
select {
case e := <-a.Events():
switch e := a.Filter(e).(type) {
case lifecycle.Event:
switch e.Crosses(lifecycle.StageVisible) {
case lifecycle.CrossOn:
glctx = e.DrawContext.(gl.Context)
onStart(glctx)
case lifecycle.CrossOff:
onStop()
glctx = nil
}
case paint.Event:
if glctx == nil || e.External {
continue
}
onDraw(glctx)
a.EndPaint(e)
case touch.Event:
if glctx == nil {
continue
}
onTouch(e)
}
}
}
})
}
gomobile bind -target=android
通過(guò)以上步驟,就可以實(shí)現(xiàn)在Go代碼中調(diào)用Android原生功能。