Search code examples
androidfilesystemsstorageandroid-fileandroid-api-levels

Using deprecated functions on older API versions?


Background: I am making my app with minimum API level 17.

I was looking up ways to get the size of the file system and saw this:

http://developer.android.com/reference/android/os/StatFs.html

However, a lot of the newer functions are only available in API level 18 upward, and the older versions are now deprecated.

How might I correctly use something like http://developer.android.com/reference/android/os/Build.VERSION.html to say, "If the user's API level is 17, use the deprecated version of these functions, but if API level is 18+, use the newer versions of these functions"? Would I need to use the deprecation annotation somehow?


Solution

  • You should use the deprecated method if the OS version is below 18 or use the newer method if the OS version is above or equals to 18.

    For example:

    @SuppressWarnings("deprecation")
    private long getAvailableBlocks(StatFs statFs) {
        long availableBlocks;
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            availableBlocks = statFs.getAvailableBlocksLong();
        } else {
            availableBlocks = statFs.getAvailableBlocks();
        }
    
        return availableBlocks;
    }