get removable sd card path in android

社会主义新天地 提交于 2019-12-10 18:48:05

问题


How can i get extSdcard path in android?

There are 2 storage, first external storage in which all the phones have it but there is second storage which is called removable storage (micro sdcard).

I want to get the path to the micro sdcard in android, how is that possible?


回答1:


Starting from KitKat, you have access to a method to get that directory :

Context.getExternalFilesDirs()

Note that it may return null if the SD card is not mounted or moved during the access. Also, you might need to add these permissions to your manifest file :

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

Apparently some users had trouble with this method, not returning the SD card path. I found some useful informations on how it can works and how it can not depending on the device on this post.




回答2:


Check this https://developer.android.com/guide/topics/data/data-storage.html#filesExternal for complete reference as you need to define permission to read and write to the external SD also there is code in the above link which checks if SD card is available before performing any action




回答3:


The following works for me!

File[] Dirs = ContextCompat.getExternalFilesDirs(this.getApplicationContext(), null);
File path = (Dirs[1]);
String pathSD = Dirs[1].toString();
int firstOpen = pathSD.indexOf("/");
int secondOpen = pathSD.indexOf("/", firstOpen + 1);
int thirdOpen = pathSD.indexOf("/", secondOpen + 1);
String filename = pathSD.substring(firstOpen, thirdOpen + 1);
path = new File(filename);


来源:https://stackoverflow.com/questions/38324985/get-removable-sd-card-path-in-android

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