问题
Since android 6.0, the sdcard path is no longer "/storage/sdcard1/", "/storage/sdcard-ext/" or something.
The path depends on the phone instead. If I use Nexus 5x AVD, the path is "/storage/1D15-3A1B/". When I use Nexus 6p AVD, the path is "/storage/4679-1802/". So how can I dynamically write the sdcard path in program to locate the file in external sdcard?
Thank you!
回答1:
Have a look at getExternalFilesDirs()
.
回答2:
It seems that I found the solution.
I'm using the access storage framework. I get it by handling the string of uri and get the "1D15-3A1B" part and then combine it to the sdcard path. Here is the solution.
- When I click the file
Welcome to Word.docx
in the sdcard root path, I get theintent
byonActivityResult()
. - Get the DocumentId by
String docId = DocumentsContract.getDocumentId(intent.getData())
, thus the stringdocId
is"1D15-3A1B:Welcome to Word.docx"
. - Split the string and get a string array by
String[] split = docId.split(":")
, so we can get"1D15-3A1B"
which issplit[0]
, and the path in sdcard"Welcome to Word.docx"
issplit[1]
. - If we want to get the uri of the file we clicked before, just need to build a new string
String newPath = "/storage/" + split[0] + "/" + split[1]
.
update:
Actually getExternalFilesDirs()
is much easier to do this...Thank you @greenapps!
回答3:
I was trying many approaches, including:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
Environment.getExternalStorageDirectory()
Still my picture files in DCIM/Camera were not visible to my app. I could see the directory names, but listFiles() on any of these directories returned null. Finally, and sheepishly, I found that my Manifest did not contain the magic line android.permission.WRITE_EXTERNAL_STORAGE. Once I added the permission, it worked like a charm.
Moral of the story: Android does not warn/break/throw exception under this condition. When it fails, it fails silently!
来源:https://stackoverflow.com/questions/38647535/can-not-locate-the-sdcard-filenot-hard-code-in-android-6-0