How can I programmatically check the amount of memory available to my Android program in Kotlin?


Part of my app involves rendering pages of a PDF into bitmaps, and potentially dozens or hundreds of pages. With a screen-sized bitmap being around 16MB, I add a buffer to only load a certain number of pages around the currently displayed page to prevent any OOM errors.

Now I'm at the point where my app is stable enough that I'd go back and have a more robust solution, dynamically determining that buffer based on available memory. At first, I thought I could Runtime to get that:

val runtime = Runtime.getRuntime() val availableHeap = runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory())

However, those numbers were all staying effectively constant (+/- a megabyte) even as I was loading hundreds of megabytes of bitmaps. The other option I read about was Debug.getNativeHeapAllocatedSize() and the corresponding getNativeHeapFreeSize(), and while the native heap allocated size went up with the bitmaps, the free size stayed constant.

That only leaves, as far as I can find, ActivityManager.MemoryInfo.totalMem, and limiting myself to some arbitrary fraction of that. That solution works and it'd be fine, but I feel like there should be a better option out there to find the hard cutoff of how much memory is given to my app.

0
May 19 at 3:00 AM
User AvatarCalvin Godfrey
#android#kotlin#memory-management

No answer found for this question yet.