ble/jni_android.go
Greg 86e724cc8c Partial android implementation, including Enable(), readyToScan(),
scan(), stopScan(), connectPeripheral(), cancelConnection(), and
DiscoverServices().
2019-11-22 16:15:02 -05:00

55 lines
985 B
Go

package ble
/*
#cgo LDFLAGS: -landroid -llog
#import "jni_android.h"
*/
import "C"
import (
"errors"
"fmt"
"log"
"runtime"
"unsafe"
)
var theJVM *C.JavaVM
type JNIEnv = C.JNIEnv
func setJVM(jvm uintptr) {
log.Printf("set theJVM")
theJVM = (*C.JavaVM)(unsafe.Pointer(jvm))
if theJVM == nil {
log.Printf("theJVM is nil!")
} else {
log.Printf("theJVM is not nil")
}
}
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)
}