Created
January 16, 2018 09:24
-
-
Save johnjohndoe/9d187871e3e9651897899700ccddcf68 to your computer and use it in GitHub Desktop.
Android: A collection of utility methods to calculate the size of a Bundle.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void logBundleState(Class<?> klass, Context context, Bundle outState) { | |
int size = getBundleSizeInBytes(outState); | |
String humanReadableSize = android.text.format.Formatter.formatFileSize(context, size); | |
Log.d(klass.getName(), "onSaveInstanceState >>> " + "bundle = " + humanReadableSize + " (" + size + " bytes)"); | |
} | |
public static int getBundleSizeInBytes(Bundle bundle) { | |
Parcel parcel = Parcel.obtain(); | |
parcel.writeValue(bundle); | |
byte[] bytes = parcel.marshall(); | |
parcel.recycle(); | |
return bytes.length; | |
} | |
public static String humanReadableByteCount(long bytes, boolean si) { | |
int unit = si ? 1000 : 1024; | |
if (bytes < unit) { | |
return bytes + " B"; | |
} | |
int exp = (int) (Math.log(bytes) / Math.log(unit)); | |
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); | |
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment