Check Available Space on SD Card on Android 5.1.1

Asked

Viewed 436 times

2

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

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 correctly, but 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 available space in the device’s internal storage and not from the memory card. Does anyone know what’s wrong with the code?

  • Hello. If you found the solution yourself, don’t edit the question to add it to it. You can even create an answer with your solution (and mark it as accepted). If you haven’t done it yet, read [help]. :)

  • 1

    Thank you Luiz, I had even done it more I thought I could not do it

1 answer

1


I found the solution in Stackoverflow in English:

https://stackoverflow.com/questions/7251793/android-absolute-location-of-external-sd-card/23744167#23744167

So I changed the method and the way I picked up 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);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.