Tuesday, September 20, 2011

Using AssetManager on native language JNI, C++

#include <sstream>
#include <assert.h>
// include in android platform-9 or newer
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
...

JNIEXPORT void JNICALL Java_com_yourpackage_yourfunctionname(JNIEnv *env, jclass clazz, jobject assetManager)
{
    // get assetmanager native
    AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
    assert(mgr != NULL);

    // load file inside assets, "assets/a/b.txt"
    AAsset* asset = AAssetManager_open(mgr, "a/b.txt", AASSET_MODE_UNKNOWN);
    assert(asset != NULL);

    // get buffer of file
    char* buff = (char*) AAsset_getBuffer(asset);
    assert(buff != NULL);

    // print out buffer per line
    const int MAX_BUF = 512;
    char strbuf [MAX_BUF];

    std::istringstream iss(buff);
    while ( iss.getline(strbuf, MAX_BUF) )
        LOGE("%s", strbuf);

    AAsset_close(asset);
}

2 comments:

  1. Any code or reference documentation showing how to call this function? It's mostly unhelpful to me as-is...

    ReplyDelete
    Replies
    1. consider the class:
      yourpackage

      public class yourpackage : extends... bla bla bla
      private static native void yourfunctionname(AssetManager mgr);




      yourfunctionname(mgr);

      Delete