Load Assets from APK on Android in NDK

Previously, for those assets like model, textures I will use ‘adb push’ command to upload them into a separate folder /data, and load them in native code. It is not good way, because I need to keep the data and program match with two deferent steps.  Actually, we could put the assets into the .apk file and them load the asset files from the .apk file.

 

APK Is ZIP file

APK is some like a ZIP file. So we need libzip to help us reading resources from the APK file. Luckily, someone already did something or us. You could download a android ndk version from here.

 

Where is APK File Path

Before you could load anything, you need to find a way to figure out where you current .APK package is. This could be done with the Java code, just as following:

String apkFilePath = "";
PackageManager packMgmr = context.getPackageManager();
try 
{
    ApplicationInfo appInfo = packMgmr.getApplicationInfo("com.easygame", 0);
    apkFilePath = appInfo.sourceDir;
} 
catch (NameNotFoundException e) 
{
    e.printStackTrace();
    throw new RuntimeException("Unable to locate assets, aborting...");
}

 

Wrap the  ZIP File Read API with a Memory File
If you check the downloaded ZIP File Read API, you will find that there is no function something like zip_fseek, only zip_fopen and zip_fread. Oh, you can not seek in file!!!
There are some solutions that you could adapt.  
a) Replace the fseek with fread, read them but discard them to seek somewhere;
b) Continue search some other libraries on the Internet that could provide seek function;
c) Read the libzip and relative code and document carefully, and write your own version;
d) Load the whole file into the memory and seek it in the memory;
……

Of course, I taken the solution d) that was the easiest one. What you need to do is load the whole file content with customize class file  open function, do memory copy with the read function and offset the memory address while do seeking.

 

Reference
http://androgeek.info/?p=275

posted @ 2012-12-24 22:05  opencoder  阅读(590)  评论(0编辑  收藏  举报