我有一些代码:
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 文件放在我的资产目录中,然后通过将 .apk 重命名为 .zip 并使用 7zip 打开它来查看 .apk 以确保它存在。
我还有一些代码:
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 目录,都找不到任何文件。
注意:DebugPrint 只是 __android_log_print() 的一个更漂亮的包装器。
我将 Activity 传递给 AAssetManager_fromJava(),而我应该传递 AssetManager。如果您将错误的类传递给 AAssetManager_fromJava(),它将失败而不会向 logcat 打印任何内容。
如何用JNI获取资产管理器:
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);
将资产管理器指针存储在某处,并从现在开始将其用于所有 AAssetManager_*() 函数。
在我的例子中,AAssetDir_getNextFileName 调用返回 NULL,因为我期望目录列表。
但是 AAssetDir_getNextFileName 不会遍历目录。 有关详细信息,请参阅https://github.com/android/ndk-samples/issues/603