Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

Write file to location other than SDcard using Android NDK?

Is there any other way to write a file somewhere else than on the SD card?

I tried many different path on the filesystem but fopen always return NULL, except for any file that I write/read inside the /sdcard/...

Is there something else equivalent to:

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

That allow you to write like on the file system or something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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 !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...