Search code examples
androidandroid-ndkandroid-10.0

How to delete file in native code passed from Java code?


I am adjusting code of my Android app (Java + native) to Android 10 Scoped Storage changes.

I declared required permissions in my manifest:

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

I launched ACTION_OPEN_DOCUMENT_TREE to let the user pick a directory.

What I do is I create file on external storage, detach file desciptor and pass to native code:

DocumentFile df = documentFile.createFile("text/plain", "my_file");
ParcelFileDescriptor pfd = getApplicationContext().getContentResolver().openFileDescriptor(df.getUri(), "rw");
myNativeFunction(pfd.detachFd());

Now, native side reads/writes from/to the file. And is responsible for closing the file descriptor.

My question is how to delete that file by native code?

Normally, in order to delete file one needs to pass pathname to it (remove(), unlink() functions take it as parameter). With Uri I failed to do that - I get "No such file or directory" error.

Thank you.


Solution

  • Thanks to CommonsWare I realized that I need to re-think my app design. So, for this case I decided to keep all the code operating on DocumentFile(s) at the Java side (including deletion) and read/write from/to files using read()/write() C functions at native side (using file descriptors previously detached from Java). In my case it is actually like that:

    1. Android app:

      • launch ACTION_OPEN_DOCUMENT_TREE to pick document tree and pass corresponding tree Uri to my Android AAR library
      • request AAR library for deletion of files under tree Uri
    2. AAR library (Java + native):

      • create DocumentFile object from passed tree Uri
      • create DocumentFile(s) under Document tree and pass file descriptors to native code (App does not have to know anything about actual files)
      • delete DocumentFile(s)