Skip to content

Instantly share code, notes, and snippets.

@johnjohndoe
Created January 16, 2018 09:24
Show Gist options
  • Save johnjohndoe/9d187871e3e9651897899700ccddcf68 to your computer and use it in GitHub Desktop.
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.
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