Can not locate the sdcard file(not hard code) in android 6.0

不打扰是莪最后的温柔 提交于 2019-12-13 23:41:58

问题


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.

  1. When I click the file Welcome to Word.docx in the sdcard root path, I get the intent by onActivityResult().
  2. Get the DocumentId by String docId = DocumentsContract.getDocumentId(intent.getData()), thus the string docId is "1D15-3A1B:Welcome to Word.docx".
  3. Split the string and get a string array by String[] split = docId.split(":"), so we can get "1D15-3A1B" which is split[0], and the path in sdcard "Welcome to Word.docx" is split[1].
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!