Android – Get free space on device

This snippet can be used to retrieve the free space (in Mb) available on a device. It may be useful especially to test when saving some file on the SD card, to make sure there is enough space for it.

public static float getMegabytesAvailable()
	{
		long bytesAvailable;
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
		if (Build.VERSION.SDK_INT < 18)
		{
			bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
		}
		else{
			bytesAvailable = (long) stat.getBlockSizeLong() * (long) stat.getAvailableBlocksLong();
		}

		return bytesAvailable / (1024.f * 1024.f);
	}

Leave a Reply

You must be logged in to post a comment.