1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
/*
#cgo LDFLAGS: -landroid
#include <jni.h>
#include <stdlib.h>
#include <string.h>
int versionCode = 0;
char versionName[16] = "";
const char* pVersionName = NULL;
int getVersion(uintptr_t java_vm, uintptr_t jni_env, jobject ctx)
{
JavaVM *vm = (JavaVM *)java_vm;
JNIEnv *env = (JNIEnv *)jni_env;
jclass ctxClazz = (*env)->FindClass(env, "android/content/Context");
jstring packageName;
jobject packageManagerObj;
jobject packageInfoObj;
jmethodID getPackageName = (*env)->GetMethodID(env, ctxClazz, "getPackageName", "()Ljava/lang/String;");
jmethodID getPackageManager = (*env)->GetMethodID(env, ctxClazz, "getPackageManager", "()Landroid/content/pm/PackageManager;");
jclass pmClazz = (*env)->FindClass(env, "android/content/pm/PackageManager");
jmethodID getPackageInfo = (*env)->GetMethodID(env, pmClazz, "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;");
jclass packageInfoClass = (*env)->FindClass(env, "android/content/pm/PackageInfo");
jfieldID versionCodeFid = (*env)->GetFieldID(env, packageInfoClass, "versionCode", "I");
jfieldID versionNameFid = (*env)->GetFieldID(env, packageInfoClass, "versionName", "Ljava/lang/String;");
packageName = (jstring)(*env)->CallObjectMethod(env, ctx, getPackageName);
packageManagerObj = (*env)->CallObjectMethod(env, ctx, getPackageManager);
packageInfoObj = (*env)->CallObjectMethod(env, packageManagerObj, getPackageInfo, packageName, 0x0);
// version code
versionCode = (*env)->GetIntField(env, packageInfoObj, versionCodeFid);
// version name
jstring jstr = (*env)->GetObjectField(env, packageInfoObj, versionNameFid);
const char *str = (*env)->GetStringUTFChars(env, jstr, NULL);
strcpy(versionName, str);
pVersionName = versionName;
(*env)->ReleaseStringUTFChars(env, jstr, str);
return versionCode;
}
*/
import "C"
var getVersionOnce sync.Once
func getVersionJni() {
e := app.RunOnJVM(func(vm, env, ctx uintptr) error {
C.getVersion(C.uintptr_t(vm), C.uintptr_t(env), C.jobject(ctx))
return nil
})
if e != nil {
log.Fatalf("getVersionJni: fatal: %s", e.Error())
}
}
func GetVersion() (v string) {
getVersionOnce.Do(getVersionJni)
log.Printf("GetVersion: versionCode: %d, versionName: %s", C.versionCode, C.GoString(C.pVersionName))
return strings.TrimSpace(C.GoString(C.pVersionName))
}
|