我正在尝试从自定义WallpaperService访问本机代码中的资产.本机代码编译并工作但尝试从传递给本机函数的AssetManager对象获取AAssetManager引用始终返回NULL.
是否与我使用服务而不是活动导致AAssetManager引用为NULL的事实有关?在Java源代码中,传递给本机函数的AssetManager是有效的,不是null.
为了测试这个,我在提供的示例和目标API级别10中使用了CubeLiveWallpaper演示.以下是为了访问本机功能而添加到CubeWallpaper1类的相关代码:
static {
System.loadLibrary("renderer");
}
private static native void load(AssetManager mgr);
@Override
public void onCreate() {
super.onCreate();
AssetManager mgr = getResources().getAssets();
load(mgr);
}
Run Code Online (Sandbox Code Playgroud)
这是我用来尝试获取有效AAssetManager引用的JNI代码:
#include <jni.h>
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#define TAG "CubeWallpaper1.c"
void
Java_com_example_android_livecubes_cube1_CubeWallpaper1_load(JNIEnv *env,
jobject assetManager) {
AAssetManager *mgr = AAssetManager_fromJava(env, assetManager);
if (mgr == NULL) {
__android_log_print(ANDROID_LOG_ERROR, "CubeWallpaper1.c", "error loading asset maanger");
} else {
__android_log_print(ANDROID_LOG_VERBOSE, "CubeWallpaper1.c", "loaded asset manager");
}
}
Run Code Online (Sandbox Code Playgroud)
这已在几台设备上复制,但大多数测试都是在运行2.3.7的HTC Desire上完成的.
我有一些代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
此代码始终在 logcat 中打印“pAsset NULL”。
我将 asset_test.txt 文件放入我的 asset 目录中,然后通过将 .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);
Run Code Online (Sandbox Code Playgroud)
该代码不打印任何内容。换句话说,无论我传入什么路径,在资产目录中都找不到文件。
注意:DebugPrint 只是 __android_log_print() 的一个看起来更漂亮的包装。
我正在使用NDK和NativeActivity编写Android应用程序.我的应用程序依赖于作为资产提供的一些第三方代码.目前我正在尝试提取这些资产,同时保持文件夹结构不变.
我已经尝试过使用AssetManager,但为了保持文件夹结构的完整性,似乎会涉及大量的代码,对于一个简单的任务,比如我所提到的.我已经转而专注于尝试将APK视为ZIP文件并以这种方式提取其内容.但这要求我找到APK的确切路径.
在普通的Android应用程序中,可以使用getPackageCodePath,但这是一个附加到Context类的抽象方法.我的问题是如何在不使用普通活动时获取APK的确切路径?
此外,我尝试通过JNI调用getPackageCodePath,但由于无法找到该方法而导致应用程序崩溃.
编辑:这甚至可能吗?