Android lollipop write to SDCard from native C ++ code
I have an Android app that uses a lot of native C ++ code. The application must work with files located on the SD card (read, create, add). But Kitkat + refused to write sdcard for third party applications. Android 5 introduced a new API that allows this again.
How to use the new SD Card Access API introduced for Android 5.0 (Lollipop)?
All examples and documentation I have found are mainly for Java. Examples for native code do not exist or are very unclear. So I want to ask a few questions.
The link above provides a valuable example of how to get the DocumentFile that ParcelFileDescriptor can return. From this object, I can get my own file descriptor - ParcelFileDescriptor.getFd (). It is an integer that I am posting to C ++ code via jni.
In C ++, I open a file using fdopen (fd).
My questions:
- Is the fdopen function working correctly, how to open a file with the new api? Or DocumentFile is already opening the file and I have to use only fd in further operations.
- Is it enough to close the file descriptor inside native code using fclose? or should I close it on the Java side using ParcelFileDescriptor.detachFd (). Or both.
thank
EDIT: I am getting FD and detachFD is working. But I never found an answer on how to properly replace ftruncate, which also needs write access, and I couldn't find a version of ftruncate that accepts a file descriptor as input
source to share
Try the links below:
Android - write / save files from native code only: Android - write / save files from native code only
Android NDK Recording File : Android NDK Recording File
File Operations in Android NDK: File Operations in Android NDK
source to share
1) yes, use file descriptors and fdopen 2)
- Open up
ParcelFileDescriptor
. - getFd ().
- Pass Fd to native code.
- Close
ParcelFileDescriptor
. (this closes your Java link)
Fd is simply int
representing the linux id for a file. In native:
- Fdopen
- Make stuff
- Fclose (note that this closes your own file pointer)
The two closures do different things.
Note. You still need SAF permission for the file or higher root.
source to share