简体   繁体   English

如何通过Android中的代码/ API查找SD卡是否存在?

[英]How to find whether the SD card is present or not via code/API in Android?

How to get the status whether a SD card is mounted/inserted in Android device or not. 是否获取SD卡是否已在Android设备中安装/插入的状态。 The following is always returning TRUE: 以下内容始终返回TRUE:

android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)

There are several post related to this, but I couldn't find a manufacturer-independent solution. 有几篇与此相关的文章,但是我找不到与制造商无关的解决方案。

Android API : Iterate through all external storages obtainable with getExternalStoragePublicDirectory , calling isExternalStorageRemovable on each of them. Android API :遍历可通过getExternalStoragePublicDirectory所有外部存储,并在每个外部存储上调用isExternalStorageRemovable When you find one, ask if it is mounted with getExternalStorageState . 找到一个时,请询问是否getExternalStorageState其安装在getExternalStorageState However, it may happen that the SD card is not used for any external storage directory and so you would not find it. 但是,可能会发生SD卡未用于任何外部存储目录的情况,因此您将找不到它。

fstab : Parse /etc/vold.fstab , find mount points, ask if they are removeable with isExternalStorageRemovable and check their state with getExternalStorageState . fstab文件 :解析/etc/vold.fstab ,找到挂载点,询问他们是否是可拆卸的带有isExternalStorageRemovable ,并检查他们的状态getExternalStorageState Because it does not use public API, it may not work correctly in some versions of Android, including future ones. 由于它不使用公共API,因此在某些版本的Android(包括将来的版本)中可能无法正常工作。 It may not work when the SD card is not used for any external storage either. 当SD卡也不用于任何外部存储时,它可能也不起作用。

mounts : Parse /proc/mounts and do the same as for fstab but that may not work if the SD card is not used for any external storage. mounts :解析/proc/mounts并执行与fstab相同的操作,但如果未将SD卡用于任何外部存储,则可能无法正常工作。 Or search for any partition using vfat but that may return false positives. 或使用vfat搜索任何分区,但可能会返回误报。 /proc/mounts is a public Linux API so it is present in the same format everywhere. /proc/mounts是公共的Linux API,因此在所有地方都以相同的格式显示。 If no SD card can be found there, it is impossible to distinguish whether the SD card is unmounted or not supported at all. 如果在该处找不到SD卡,则无法区分SD卡是否已卸下或完全不受支持。

However, there's really no reason to need that (and that's why there is no simple API for it). 但是,实际上没有理由需要它(这就是为什么没有简单的API的原因)。 When you want to put some content in an external storage, you should use the appropriate directory provided by getExternalStoragePublicDirectory , disregarding whether it is an SD card or not. 如果要将某些内容放入外部存储中,则应使用getExternalStoragePublicDirectory提供的适当目录,而不getExternalStoragePublicDirectory是否是SD卡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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