我有一些代码:
AAsset* pAsset = AAssetManager_open(pAssetManager, "asset_test.txt", AASSET_MODE_STREAMING);
DebugPrint(pAsset?"pAsset not NULL\n":"pAsset NULL");
if (pAsset)
{
char buf[1024];
AAsset_read(pAsset, buf, sizeof(buf));
DebugPrint(buf);
AAsset_close(pAsset);
}
此代码始终在 logcat 中打印“pAsset NULL”。
我将 asset_test.txt 文件放在我的 Assets 目录中,然后查看 .apk 以确保它存在,方法是将 .apk 重命名为 .zip 并使用 7zip 打开它。
我还有一些代码:
AAssetDir* pAssetDir = AAssetManager_openDir(pAssetManager, sDirectory.c_str());
if (!pAssetDir)
{
DebugPrint("pAssetDir NULL\n");
return;
}
const char* pszDir;
while ((pszDir = AAssetDir_getNextFileName(pAssetDir)) != NULL)
{
DebugPrint(pszDir);
}
AAssetDir_close(pAssetDir);
此代码不打印任何内容。换句话说,无论我将什么路径传递到 Assets 目录中,都不会在 Assets 目录中找到任何文件。
注意:DebugPrint 只是 __android_log_print() 的一个看起来更漂亮的包装器。
最佳答案
我将 Activity 传递给了 AAssetManager_fromJava(),而我应该传递了 AssetManager。如果您将错误的类传递给 AAssetManager_fromJava(),它将失败,不会向 logcat 打印任何内容。
如何使用 JNI 获取 Assets 管理器:
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
jobject activity = (jobject)SDL_AndroidGetActivity();
jclass activity_class = env->GetObjectClass(activity);
jmethodID activity_class_getAssets = env->GetMethodID(activity_class, "getAssets", "()Landroid/content/res/AssetManager;");
jobject asset_manager = env->CallObjectMethod(activity, activity_class_getAssets); // activity.getAssets();
global_asset_manager = env->NewGlobalRef(asset_manager);
pAssetManager = AAssetManager_fromJava(env, global_asset_manager);
将 Assets 管理器指针存储在某处,并从现在开始将其用于所有 AAssetManager_*() 函数。
关于安卓NDK : Why is AAssetManager_open returning NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22436259/