2019-10-28 12:43:33 -04:00
|
|
|
package ble
|
|
|
|
|
|
|
|
/*
|
2019-10-28 15:18:18 -04:00
|
|
|
#cgo LDFLAGS: -landroid -llog
|
2019-10-28 12:43:33 -04:00
|
|
|
|
2019-11-22 16:15:02 -05:00
|
|
|
#import "jni_android.h"
|
2019-10-28 12:43:33 -04:00
|
|
|
*/
|
|
|
|
import "C"
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"runtime"
|
|
|
|
"unsafe"
|
|
|
|
)
|
|
|
|
|
|
|
|
var theJVM *C.JavaVM
|
|
|
|
|
|
|
|
type JNIEnv = C.JNIEnv
|
|
|
|
|
2019-11-22 16:15:02 -05:00
|
|
|
func setJVM(jvm uintptr) {
|
|
|
|
log.Printf("set theJVM")
|
2019-10-28 12:43:33 -04:00
|
|
|
theJVM = (*C.JavaVM)(unsafe.Pointer(jvm))
|
2019-11-22 16:15:02 -05:00
|
|
|
if theJVM == nil {
|
|
|
|
log.Printf("theJVM is nil!")
|
|
|
|
} else {
|
|
|
|
log.Printf("theJVM is not nil")
|
|
|
|
}
|
2019-10-28 12:43:33 -04:00
|
|
|
}
|
|
|
|
|
2019-11-22 16:15:02 -05:00
|
|
|
func runInJVM(f func(env *C.JNIEnv)) {
|
2019-10-28 12:43:33 -04:00
|
|
|
runtime.LockOSThread()
|
|
|
|
defer runtime.UnlockOSThread()
|
|
|
|
var env *C.JNIEnv
|
|
|
|
var detach bool
|
2019-10-28 15:18:18 -04:00
|
|
|
//log.Printf("RunInJVM(): theJVM = %d", uintptr(unsafe.Pointer(theJVM)))
|
2019-10-28 12:43:33 -04:00
|
|
|
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)
|
|
|
|
}
|