Android NDK: 为什么AAssetManager_open返回NULL?

4

我有一些代码:

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重命名为.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);

这段代码没有输出任何内容。换句话说,无论我传入什么路径,都无法在资产目录中获取到任何文件。

注意:DebugPrint只是对__android_log_print()的美化包装。

2个回答

6
我将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_*()函数。


1
SDL_AndroidGetJNIEnv的库是什么? - Talha Ç

0
在我的情况下,AAssetDir_getNextFileName调用返回了NULL,因为我期望得到目录列表。
但是AAssetDir_getNextFileName不会迭代目录。 有关更多详细信息,请参见https://github.com/android/ndk-samples/issues/603

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接