Check Available SD card space on Android 5.1.1

2

I need to check the amount of space available on the memory card, I currently use this method for verification:

public static float megabytesAvailable() {
        File f = Environment.getExternalStorageDirectory()
        StatFs stat = new StatFs(f.getPath());
        long bytesAvailable = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
        }
        else {
            bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
        }
        return bytesAvailable / (1024.f * 1024.f * 1024.f);
}

For older versions (up to 4.3.3) is working properly, however when I run this same method on a Galaxy Grand Prime Duos (SM-G531H) with version 5.1.1 of Android, the above method returns me the space available on the device's internal storage and not on the memory card. Does anyone know what's wrong with the code?

    
asked by anonymous 01.02.2016 / 19:15

1 answer

1

I found the solution in Stackoverflow in English:

link

So I changed the method and the way I got the memory card:

    public static String getCaminhoSdCard() {
        String lstrDir = System.getenv("SECONDARY_STORAGE");

        if (lstrDir == null || lstrDir.isEmpty())
            return "";

        if (lstrDir.contains(":"))
            return lstrDir.substring(0, lstrDir.indexOf(":"));

        return lstrDir;
    }

    public static float megabytesAvailable() {
        StatFs stat = new StatFs(getCaminhoSdCard());
        long bytesAvailable = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
        }
        else {
            bytesAvailable = (long)stat.getBlockSize() * (long)stat.getAvailableBlocks();
        }
        return bytesAvailable / (1024.f * 1024.f * 1024.f);
    }
    
02.02.2016 / 11:57