user1063364
user1063364

Reputation: 917

Android lollipop write to sdcard from native code c++

I have android application which uses a lot of c++ native code. Application needs to work with files located on sdcard(read, create, append). But Kitkat+ denied writing to sdcard for 3rd party applications. Android 5 introduced new API which allows that again.

How to use the new SD card access API presented for Android 5.0 (Lollipop)?

All examples and documentation what I found are mostly for Java side. Examples for native code don't exist or are very unclear. So I want ask few questions.

The link above contains valuable example how to get DocumentFile which can return ParcelFileDescriptor. From this object I am able to receive native file descriptor - ParcelFileDescriptor.getFd(). It's integer which I am sending to c++ code through jni.

In c++ I am opening file with fdopen(fd).

My questions are :

  1. Is fdopen function correct way how to open the file with new api? Or the DocumentFile already opens the file and I should only use fd in further operations.
  2. It's enough to close the file descriptor inside native code with fclose? or should I close it on java side with ParcelFileDescriptor.detachFd(). Or both.

Thank you

EDIT : I getFD and detachFD works. But I never found answer how to correctly replace ftruncate, which needs write access too, and I did not found ftruncate version which takes file descriptor like a input

Upvotes: 3

Views: 3536

Answers (2)

Anthony
Anthony

Reputation: 7828

1) yes, use file descriptors and fdopen 2)

  1. Open the ParcelFileDescriptor.
  2. getFd().
  3. Pass the Fd to native code.
  4. Close the ParcelFileDescriptor. (this is closing your java reference)

Fd is just an int representing a linux id for a file. In native:

  1. Fdopen
  2. Do stuff
  3. Fclose (note this is closing your native file pointer)

The two closes are doing different things.

Note: You still need the SAF permission for the file or a higher root.

Upvotes: 0

Anil Kongovi
Anil Kongovi

Reputation: 49

Try Below Links:

Android - writing/saving files from native code only: Android - writing/saving files from native code only

Android NDK Write File: Android NDK Write File

File Operations in Android NDK: File Operations in Android NDK

Upvotes: -1

Related Questions