Add JNI example.

This commit is contained in:
Greg 2019-10-18 14:40:35 -04:00
parent c79040a961
commit dad071293c
10 changed files with 322 additions and 34 deletions

View File

@ -10,3 +10,18 @@ cd $GOPATH/src/git.wow.st/gmp/android-go/examples/sensors
gogio -target android -minsdk 27 .
adb install -r sensors.apk
```
There is also an example showing how to incorporate custom Java classes
and access them (and the rest of the Android system) via JNI. To build it
(on a Unix-like environment):
```
go get git.wow.st/gmp/android-go/examples/jni
cd $GOPATH/src/git.wow.st/gmp/android-go/examples/jni
go generate os_android.go
gogio -target android -minsdk 27 .
adb install -r jni.apk
```
To build on Windows, you will need to re-write the `go:generate` commands
at the top of `os_android.go` as appropriate.

9
examples/jni/AClass.java Normal file
View File

@ -0,0 +1,9 @@
package st.wow.git.jni;
public class AClass {
public int Num() {
return 17;
}
}

130
examples/jni/jni_android.go Normal file
View File

@ -0,0 +1,130 @@
package main
/*
#cgo LDFLAGS: -landroid
#include <stdlib.h>
#include <jni.h>
#include <android/log.h>
static jobject gClassLoader;
static jmethodID gFindClassMethod;
void
SetLoader(JNIEnv* env, jobject context) {
jclass cclass = (*env)->GetObjectClass(env, context);
jmethodID gcl_id = (*env)->GetMethodID(env, cclass, "getClassLoader", "()Ljava/lang/ClassLoader;");
jobject loader = (*env)->CallObjectMethod(env, context, gcl_id);
gClassLoader = (*env)->NewGlobalRef(env, loader);
jclass lclass = (*env)->GetObjectClass(env, loader);
gFindClassMethod = (*env)->GetMethodID(env, lclass, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
}
jclass
FindClass(JNIEnv* env, char* name) {
jstring strClassName = (*env)->NewStringUTF(env, name);
return (*env)->CallObjectMethod(env, gClassLoader, gFindClassMethod, strClassName);
}
JNIEXPORT jobject
CreateObject(JNIEnv* env, jclass cls) {
jmethodID init = (*env)->GetMethodID(env, cls, "<init>", "()V");
return (*env)->NewObject(env, cls, init);
}
void CallVoidMethod(JNIEnv *env, jobject obj, jmethodID methodID) {
(*env)->CallVoidMethod(env, obj, methodID);
}
jint CallIntMethod(JNIEnv *env, jobject obj, jmethodID methodID) {
return (*env)->CallIntMethod(env, obj, methodID);
}
jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig) {
return (*env)->GetMethodID(env, clazz, name, sig);
}
jint GetEnv(JavaVM *vm, JNIEnv **env, jint version) {
return (*vm)->GetEnv(vm, (void **)env, version);
}
jint AttachCurrentThread(JavaVM *vm, JNIEnv **p_env, void *thr_args) {
return (*vm)->AttachCurrentThread(vm, p_env, thr_args);
}
jint DetachCurrentThread(JavaVM *vm) {
return (*vm)->DetachCurrentThread(vm);
}
*/
import "C"
import (
"errors"
"fmt"
"log"
"runtime"
"unsafe"
)
var theJVM *C.JavaVM
type JNIEnv = C.JNIEnv
func SetJVM(jvm, context uintptr) {
log.Print("set theJVM")
theJVM = (*C.JavaVM)(unsafe.Pointer(jvm))
log.Printf("theJVM = %d", uintptr(unsafe.Pointer(theJVM)))
RunInJVM(func(env *C.JNIEnv) {
C.SetLoader(env, (C.jobject)(context))
})
}
func FindClass(env *C.JNIEnv, name string) C.jclass {
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
return C.FindClass((*C.JNIEnv)(env), cname)
}
func JniCallVoidMethod(env *C.JNIEnv, obj C.jobject, methodID C.jmethodID) {
C.CallVoidMethod(env, obj, methodID)
}
func JniCallIntMethod(env *C.JNIEnv, obj C.jobject, methodID C.jmethodID) int {
return (int)(C.CallIntMethod(env, obj, methodID))
}
func JniGetMethodID(env *C.JNIEnv, cls C.jclass, name, sig string) C.jmethodID {
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
csig := C.CString(sig)
defer C.free(unsafe.Pointer(csig))
return C.GetMethodID(env, cls, cname, csig)
}
func CreateObject(env *C.JNIEnv, cls C.jclass) C.jobject {
return C.CreateObject(env, (C.jclass)(cls))
}
func RunInJVM(f func(env *C.JNIEnv)) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var env *C.JNIEnv
var detach bool
log.Printf("RunInJVM(): theJVM = %d", uintptr(unsafe.Pointer(theJVM)))
if res := C.GetEnv(theJVM, &env, C.JNI_VERSION_1_6); res != C.JNI_OK {
if res != C.JNI_EDETACHED {
panic(fmt.Errorf("JNI GetEnv failed with error %d", res))
}
if C.AttachCurrentThread(theJVM, &env, nil) != C.JNI_OK {
panic(errors.New("runInJVM: AttachCurrentThread failed"))
}
detach = true
}
if detach {
defer func() {
C.DetachCurrentThread(theJVM)
}()
}
f(env)
}

80
examples/jni/main.go Normal file
View File

@ -0,0 +1,80 @@
// +build darwin linux
package main
import (
"log"
"gioui.org/app"
"gioui.org/io/system"
"gioui.org/layout"
"gioui.org/unit"
"gioui.org/widget/material"
_ "gioui.org/font/gofont"
)
var (
labchan chan string
)
func main() {
labchan = make(chan string)
log.Print("Staring event loop")
go eventloop()
app.Main()
log.Print("app.Main() returned")
}
func diffInsets(x, y system.Insets) bool {
return x.Top != y.Top ||
x.Bottom != y.Bottom ||
x.Left != y.Left ||
x.Right != y.Right
}
func eventloop() {
w := app.NewWindow(
app.Size(unit.Dp(400), unit.Dp(400)),
app.Title("Hello"))
th := material.NewTheme()
gtx := &layout.Context{Queue: w.Queue()}
sysinset := &layout.Inset{}
margin := layout.UniformInset(unit.Dp(10))
labels := []material.Label{}
list := &layout.List{Axis: layout.Vertical}
resetSysinset := func(x system.Insets) {
sysinset.Top = x.Top
sysinset.Bottom = x.Bottom
sysinset.Left = x.Left
sysinset.Right = x.Right
}
go func() {
labchan <- "Starting"
callJni()
}()
for {
select {
case x := <-labchan:
labels = append(labels, th.Body1(x))
case e := <-w.Events():
switch e := e.(type) {
case system.DestroyEvent:
return
case system.FrameEvent:
gtx.Reset(e.Config, e.Size)
resetSysinset(e.Insets)
sysinset.Layout(gtx, func() {
margin.Layout(gtx, func() {
list.Layout(gtx, len(labels), func(i int) {
labels[i].Layout(gtx)
})
})
})
e.Frame(gtx.Ops)
}
}
}
}

View File

@ -0,0 +1,39 @@
//go:generate javac -bootclasspath $ANDROID_HOME/platforms/android-29/android.jar AClass.java
//go:generate jar cf AClass.jar AClass.class
//go:generate rm AClass.class
package main
import (
"fmt"
"log"
"time"
"gioui.org/app"
)
func callJni() {
time.Sleep(time.Second/5)
h := app.PlatformHandle()
labchan <- fmt.Sprintf("JVM = %d", h.JVM)
labchan <- fmt.Sprintf("Context = %d", h.Context)
SetJVM(h.JVM, h.Context)
RunInJVM(func(env *JNIEnv) {
log.Print("finding class")
cls := FindClass(env, "st/wow/git/jni/AClass")
log.Print("getting methodID")
mth := JniGetMethodID(env, cls, "Num", "()I")
if mth == nil {
labchan <- "nil method"
return
}
log.Print("creating object")
inst := CreateObject(env, cls)
log.Print("calling method")
val := JniCallIntMethod(env, inst, mth)
log.Print("got result")
labchan <- fmt.Sprintf("val = %d", val)
})
}

7
examples/jni/os_other.go Normal file
View File

@ -0,0 +1,7 @@
// +build !android
package main
func callJni() {
}

View File

@ -3,25 +3,18 @@
package main
import (
"image/color"
"log"
"gioui.org/app"
"gioui.org/io/system"
"gioui.org/layout"
"gioui.org/text"
"gioui.org/text/shape"
"gioui.org/unit"
"gioui.org/widget/material"
"golang.org/x/image/font/gofont/goregular"
"golang.org/x/image/font/sfnt"
_ "gioui.org/font/gofont"
)
var (
face text.Face
white = color.RGBA{A: 0xff, R: 0xff, G: 0xff, B: 0xff}
gray = color.RGBA{A: 0xff, R: 0xb0, G: 0xb0, B: 0xb0}
black = color.RGBA{A: 0xff, R: 0x00, G: 0x00, B: 0x00}
labchan chan string
)
@ -33,7 +26,7 @@ func main() {
log.Print("App closed")
}
func diffInsets(x, y app.Insets) bool {
func diffInsets(x, y system.Insets) bool {
return x.Top != y.Top ||
x.Bottom != y.Bottom ||
x.Left != y.Left ||
@ -42,41 +35,36 @@ func diffInsets(x, y app.Insets) bool {
func eventloop() {
w := app.NewWindow(
app.WithWidth(unit.Dp(400)),
app.WithHeight(unit.Dp(400)),
app.WithTitle("Hello"))
app.Size(unit.Dp(400), unit.Dp(400)),
app.Title("Hello"))
th := material.NewTheme()
gtx := &layout.Context{Queue: w.Queue()}
var faces shape.Faces
regular, err := sfnt.Parse(goregular.TTF)
if err != nil {
log.Fatal("Cannot parse font.")
}
face = faces.For(regular, unit.Sp(16))
sysinset := &layout.Inset{}
margin := layout.UniformInset(unit.Dp(10))
labels := []*text.Label{}
labels := []material.Label{}
list := &layout.List{Axis: layout.Vertical}
resetSysinset := func(x app.Insets) {
resetSysinset := func(x system.Insets) {
sysinset.Top = x.Top
sysinset.Bottom = x.Bottom
sysinset.Left = x.Left
sysinset.Right = x.Right
}
go func() {
labchan <- "Starting"
}()
for {
select {
case x := <-labchan:
labels = append(labels, &text.Label{Face: face, Text: x})
labels = append(labels, th.Body1(x))
case e := <-w.Events():
switch e := e.(type) {
case app.DestroyEvent:
case system.DestroyEvent:
return
case app.UpdateEvent:
gtx.Reset(&e.Config, e.Size)
faces.Reset(&e.Config)
case system.FrameEvent:
gtx.Reset(e.Config, e.Size)
resetSysinset(e.Insets)
sysinset.Layout(gtx, func() {
margin.Layout(gtx, func() {
@ -85,7 +73,7 @@ func eventloop() {
})
})
})
w.Update(gtx.Ops)
e.Frame(gtx.Ops)
}
}
}

View File

@ -1,9 +1,5 @@
//+build android
package main
import "C"
import (
"fmt"
"log"

2
go.mod
View File

@ -3,6 +3,6 @@ module git.wow.st/gmp/android-go
go 1.13
require (
gioui.org v0.0.0-20191003113651-f3819d816490
gioui.org v0.0.0-20191018181617-5ef176af8145
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a
)

24
go.sum
View File

@ -1,9 +1,33 @@
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
gioui.org v0.0.0-20191003113651-f3819d816490 h1:gEVjHOvnfHdfOiPCTMQuwFp5iceBK/i8QcVd44F1ejs=
gioui.org v0.0.0-20191003113651-f3819d816490/go.mod h1:+CEjc9B//HrBfWsQOVxjCyih7HGIj3Pww1xFHVDZyyk=
gioui.org v0.0.0-20191018144543-175144fa99b5 h1:gLTisL9HKeXoYbSXXEe6SRhy1K+FsZEyUmlnxCzIQoE=
gioui.org v0.0.0-20191018144543-175144fa99b5/go.mod h1:KqFFi2Dq5gYA3FJ0sDOt8OBXoMsuxMtE8v2f0JExXAY=
gioui.org v0.0.0-20191018181617-5ef176af8145 h1:7zU3Wky5H9jKAhHLsc4Zbs5uDcIh3WmW4HdnPhz997A=
gioui.org v0.0.0-20191018181617-5ef176af8145/go.mod h1:KqFFi2Dq5gYA3FJ0sDOt8OBXoMsuxMtE8v2f0JExXAY=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3 h1:n9HxLrNxWWtEb1cA950nuEEj3QnKbtsCJ6KjcgisNUs=
golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190703141733-d6a02ce849c9/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a h1:gHevYm0pO4QUbwy8Dmdr01R5r1BuKtfYqRqF0h/Cbh0=
golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=