Write file to location other than SDcard using Android NDK?

  1. You can always access the directory
    in which your app is placed.

    This directory is usually :

    data/data/<Your_package_name_usually
    com.android.appName>/files/<your_filename>

    but better use getFilesDir() to
    ensure valid filepath with future
    version changes of android.

  2. If you wanna use external storage
    instead, make sure you place this
    line of code in your app manifest to
    gain permission.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    

    Then use the sdcard directory :

    getExternalStorageDirectory();
    //usually : /sdcard/<your_filename>

  3. Otherwise, you can root the device
    and gain access to the whole
    filesystem. But you’ll have to
    request all of your app users to get
    root access on their device before
    using your application. Some games
    use this way of doing things, but I
    wouldn’t recommend it. If you still
    wanna do this, lookup Superuser
    app for android, it’s free and
    trustable.

Once you have the android directory, just create a JNI native method that receive a jstring parameter, and you set it up inside your native code. Convert it into a std::string, and you’ll be ready to use it with fopen().

//Inside your java activity
File f = this.getApplicationContext().getFilesDir(); 
LibLoader.setupArchiveDir(f.toString());

//Inside your JNI wrapper
JNIEXPORT bool JNICALL Java_com_android_appName_LibLoader_setupArchiveDir(JNIEnv * env, jobject obj, jstring dir)
{
        const char* temp = env->GetStringUTFChars(dir, NULL);
    std::string stringDir(temp);

        // Will be receive as a std::string inside C++ code 
    MyNativeObjectInC++->SetupArchiveDir(stringDir);
}

Edit :

You might need to manualy creates the /files in C before being able to use it on the first time :

int result_code = mkdir("/data/data/com.app/files/", 0770)

Cheers !

Leave a Comment