简体   繁体   中英

Android: How to get storage of external sd-card?

In my device I have 32GB internal memory and 64GB on SD-Card. I like to get the external free size with this method (based on this thread Android get free size of internal/external memory ):

public static long getAvailableExternalMemorySize() {
    if (externalMemoryAvailable()) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;

    } else {
        return 0;
    }
}

When I run this code it only shows me the free storage of internal memory. Why does it not shows the external SD-Card size? On Device Storage I have 11GB free and on external SD-Card there are 40GB free.

Problem is that there is no api to access external sd cards on android. On android >= 4.4 external sd cards cannot be written to.

The only thing you could do (VERY SPECIAL, not recommended for public apps, but doable in a restricted environment!), if you're certain the devices are < android 4.4: Keep a list of paths that you have seen to work so far on many devices and check all of them for existance properly. Maybe you get lucky.

I found a solution to read the storage of removable sd-card:

This method retourns the free memory size on removable sd-card in byte.

public static long getFreeExternalMemorySize() {
        String secStore = System.getenv("SECONDARY_STORAGE");
        File path = new File(secStore);
        StatFs stat = new StatFs(path.getPath());

        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();

        return availableBlocks * blockSize;
}

You can get an idea after reading the following links.

http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

for handling sd card. Check whether sd card is mounted before you access.

http://developer.android.com/training/basics/data-storage/files.html#WriteExternalStorage

Check sd card is writable and readable.

http://developer.android.com/training/basics/data-storage/files.html#GetFreeSpace

to get the free space in sdcard or internal storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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