简体   繁体   中英

Opening Files from a String Path with Android NDK

I've been going over the Android file access documentation lately, but I seem to be unable to figure out how to actually open a file given as a string containing the path to the file I'd like to open.

What I (eventually) want to accomplish is something like this:

  1. The user selects a specific kind of text file using Intents, receiving a URI to the file. From this I derive the path ( getPath() ) and pass this string to the native C++ code.
  2. The native C++ opens the file from the string, parsing the content.
  3. Perform some actual work with the above.

From what I've found so far, it seems like it is no longer possible to open files this way (as of SDK version 26 at least):

  • A hard-coded path to a file I know exists gives me permission denied .
  • The path itself received from getPath() triggers a No such file or directory error.

One workaround called for opening the file on the Java side using the ContentResolver , and then passing the file descriptor to the native side. This works, but it's problematic: the files can contain references to other files to be opened ("include files") making such a solution of limited use.

Just to make things clear, these files reside locally on the "USB" partition of the Android system, unrelated to the app itself. Not as resources/assets to the APK or anything similar which other questions of this kind seem to require.

In summary, I guess the question is this: Is it possible to open a file, and possibly any other files it refers to, given a path from the Java side of the application? Is there any requirements for doing this, such as requesting the correct permissions for folders or something similar?

As of Android 6.0 (API level 23) you need to request permissions every time your app starts for " dangerous actions " such as accessing the filesystem or reading contacts. The linked pages already have a snippet of code you can copy.

On older phones requesting permissions in the manifest was sufficient, but the target SDK version was recenly upped to 8.0 (=26). If you want to support devices pre-6.0, the Android compatibility library will allow you to call the same API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM