android: finding if sd-card is present

2019-06-28 04:25发布

I am having a problem. I have a galaxy tab that comes with 16gb of internal storage and 2 gb of sd-card card.

when I use environment.getExternalStorageState, it returns mounted. However, when I remove the sd-card from my galaxy tab, it still returns mounted because it considers the internal storage as the external storage. Is there any way in which I can differentiate between the actual SD-Card and the Internal Storage?

Thanks

5条回答
我命由我不由天
2楼-- · 2019-06-28 05:01

I try like this

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

    Log.i("tag", "SDCard is mounted");

    }

or this example would help you

查看更多
孤傲高冷的网名
3楼-- · 2019-06-28 05:04

You might be able to determine the sd card's mount path and if its not related to the system then its probably external media. Try checking out this link here:

Find an external SD card location

查看更多
我只想做你的唯一
4楼-- · 2019-06-28 05:06

There doesn't seem to be any public API for this currently. You could check by looking at /proc/mounts but your code would then be device-dependent, since not all devices mount secondary external storage (SD card) at the same place.

查看更多
甜甜的少女心
5楼-- · 2019-06-28 05:14

I've created a check of my own, and it works. It checks if secondary, real SD card is present. Tested it on Samsung Galaxy s5 neo, Alcatel one touch 5020x, and on HTC One X. The code should work on KITKAT devices since it uses the app default dir to check.

I create a String of default app path storage on primary storage. Then change "primary" to "secondary", then try to create a folder and check for existance.

Heres the code:

String primaryStorage = Environment.getExternalStorageDirectory().getAbsolutePath();
String secondaryStorage = System.getenv("SECONDARY_STORAGE");
Boolean hasSecondary = false;

String internalSD = getExternalFilesDir(null) + "/test";
String externalSD = internalSD.replace(primaryStorage, secondaryStorage);

            try{
                File dir = new File(externalSD);
                dir.mkdirs();

                if (dir.isDirectory()) {
                    dir.delete();
                    hasSecondary = true;
                }                   
            } catch (Exception e) {
            }
查看更多
\"骚年 ilove
6楼-- · 2019-06-28 05:15

I think /storage/sdcard0/ is used for internal sdcard and /storage/sdcard1/ is used for external sd card if there are two storage option present. if you are checking a file is present either in any of sdcard or not you should check all possible paths.

String path;    
if(new File("/mnt/sdcard/yourpath").exists()) {
    path="/storage/sdcard/yourpath";
} else if(new File("/storage/sdcard0/yourpath").exists()) {
    path="/storage/sdcard0/yourpath";
} else if(new File("/storage/sdcard1/yourpath").exists()) {
    path="/storage/sdcard1/yourpath";
}
查看更多
登录 后发表回答