13

Is there a way to get the application's directory to save private data to a file for my application directly from the NDK? In other words, I need an equivalent of the Java function mContext.getFilesDir().

I have noted that other posts such as this one: Android NDK Write File

mention what is the 'usual' place for this directory to be. But for it to be correct in all versions and all devices, an equivalent system call is surely necessary.

I am currently using a NativeActivity and no Java at all.

Thank you for your time.

Community
  • 1
  • 1
DJPJ
  • 319
  • 1
  • 4
  • 13

2 Answers2

11

I have custom helper class for accessing various paths, for the data directory I do this:

  1. Read /proc/self/cmdline or /proc/**MyPID**/cmdline
  2. Append the results from #1 to /data/data/

Example results:

/data/data/com.yourcompany.yourproduct/
frogatto
  • 28,539
  • 11
  • 83
  • 129
NuSkooler
  • 5,391
  • 1
  • 34
  • 58
  • 3
    For those wondering how to get the `MyPID`, you could simply substitute that with "self', i.e. read `/proc/self/cmdline` and that will save you a bit of extra hassle. – MultiColourPixel Nov 01 '16 at 22:42
  • @MultiColourPixel Good point, I have updated the answer to show both. – NuSkooler Nov 02 '16 at 17:05
6

If you are using NativeActivity then you have access from native code to an ANativeActivity instance (see <ndk_root>/platforms/android-9/arch-arm/usr/include/android/native_activity.h) which has internalDataPath and externalDataPath members.

frogatto
  • 28,539
  • 11
  • 83
  • 129
jimkberry
  • 1,317
  • 7
  • 8
  • 1
    Thank you, this is exactly what I was looking for. Unfortunately both internalDataPath and externalDataPath are NULL during runtime..? Any ideas? This is when running on a google nexus S device. – DJPJ Jun 09 '11 at 08:45
  • 1
    ok according to this link: http://groups.google.com/group/android-ndk/browse_thread/thread/e250fc392fb0e145?pli=1 it is a known bug with android 2.3.x and it is fixed in 3.0. Great! So I'll need to look into implementing jni just for this... – DJPJ Jun 09 '11 at 09:09
  • I went down that same route and, after looking at the spread of installed device OS versions realized that I simply couldn't ignore v2.1. So NativeActivity became a non-issue. As it turns out, implementing a full JNI shim is pretty straightforward, and has the added advantage that whenever you find something that NativeActivity has left out, you;re already set up to add it. – jimkberry Jun 09 '11 at 13:09