diff --git a/app/android.c b/app/android.c index 29b2794..1e4785c 100644 --- a/app/android.c +++ b/app/android.c @@ -4,6 +4,7 @@ // +build android +#include #include #include #include @@ -210,6 +211,18 @@ void ANativeActivity_onCreate(ANativeActivity *activity, void* savedState, size_ JNIEXPORT void JNICALL Java_go_Go_run(JNIEnv* env, jclass clazz, jobject ctx) { current_ctx = (*env)->NewGlobalRef(env, ctx); + + if (current_ctx != NULL) { + // Init asset_manager. + jclass context_clazz = find_class(env, "android/content/Context"); + jmethodID getassets = find_method( + env, context_clazz, "getAssets", "()Landroid/content/res/AssetManager;"); + // Prevent the java AssetManager from being GC'd + jobject asset_manager_ref = (*env)->NewGlobalRef( + env, (*env)->CallObjectMethod(env, current_ctx, getassets)); + asset_manager = AAssetManager_fromJava(env, asset_manager_ref); + } + init_go_runtime(NULL); } diff --git a/app/android.go b/app/android.go index 4b85413..0a8d5a9 100644 --- a/app/android.go +++ b/app/android.go @@ -40,6 +40,11 @@ jobject current_ctx; // current_native_activity is the Android ANativeActivity. May be NULL. ANativeActivity* current_native_activity; +// asset_manager is the asset manager of the app. +// For all-Go app, this is initialized in onCreate. +// For go library app, this is set from the context passed to Go.run. +AAssetManager* asset_manager; + // build_auxv builds an ELF auxiliary vector for initializing the Go // runtime. While there does not appear to be any spec for this // format, there are some notes in @@ -67,11 +72,9 @@ import ( "golang.org/x/mobile/geom" ) -var assetManager *C.AAssetManager - //export onCreate func onCreate(activity *C.ANativeActivity) { - assetManager = activity.assetManager + C.asset_manager = activity.assetManager config := C.AConfiguration_new() C.AConfiguration_fromAssetManager(config, activity.assetManager) @@ -192,7 +195,7 @@ func openAsset(name string) (ReadSeekCloser, error) { cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) a := &asset{ - ptr: C.AAssetManager_open(assetManager, cname, C.AASSET_MODE_UNKNOWN), + ptr: C.AAssetManager_open(C.asset_manager, cname, C.AASSET_MODE_UNKNOWN), name: name, } if a.ptr == nil {