蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

8.2.2 Bitmap 引起的 OOM 问题

剖析 Android 应用堆内存上限与 OOM 成因,对比像素编码降耗、inJustDecodeBounds + inSampleSize 两步采样、及时回收、SoftReference 及 LruCache 内存缓存方案。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

OOM 成因与虚拟机堆内存上限

OOM(Out Of Memory,内存溢出)源于单个应用进程申请的内存总量超出了 Android 虚拟机(Dalvik/ART)为其划定的最大堆上限,与设备总物理 RAM 是否尚有空闲无关(物理 RAM 耗尽通常触发系统 LMK 杀进程而非单纯抛出应用内 OOM)。可通过 `ActivityManager.getMemoryClass()`、`adb shell getprop | grep dalvik.vm.heapgrowthlimit` 或查阅 `/system/build.prop` 了解三个关键参数:`dalvik.vm.heapstartsize`(初始堆大小,如 `8m`)、`dalvik.vm.heapgrowthlimit`(标准应用最大堆上限,如 `192m`)以及 `dalvik.vm.heapsize`(清单声明 `android:largeHeap="true"` 后的扩容上限,如 `512m`)。

降低位图内存占用:像素格式与两步采样压缩

减少单张 `Bitmap` 体积的首要手段是按需选择低位深 `inPreferredConfig`。默认的 `Bitmap.Config.ARGB_8888` 每像素占 32 位(4 字节),若改为 16 位格式(每像素 2 字节)即可直接减半内存占用。需注意原文提及的 `ARGB_4444` 因画质较差已在 API 13 废弃,对无需透明通道的照片应优先选用 `Bitmap.Config.RGB_565`。

其次是通过 `BitmapFactory.Options` 执行两步降采样:第一轮置 `inJustDecodeBounds = true` 解码,不分配像素内存而读取原图 `outWidth`/`outHeight`;据此结合目标控件宽高计算 `inSampleSize`(Android 解码器向下取最接近的 2 的幂次);第二轮重置 `inJustDecodeBounds = false` 正式解码并捕获潜在 `OutOfMemoryError`(注:示例中的 `inPurgeable`/`inInputShareable` 已在 API 21 废弃)。对于引导页大图、帧动画等生命周期明确的资源,不再展示时应及时解除引用(如 `imageView.setImageDrawable(null)`)并在旧版系统中按需调用 `recycle()`。

SoftReference 与 LruCache 内存缓存机制

为避免频繁加载、释放同一张图片造成卡顿,早期方案使用 `HashMap<String, SoftReference<Bitmap>>` 软引用缓存,期望由 GC 在内存紧张时自动回收。但自 Android 2.3(API 9)起垃圾回收器对软/弱引用的回收策略变得更激进,导致 `SoftReference` 缓存命中率不稳定,官方不再推荐作为主力图片缓存。

自 Android 3.1 起官方提供 `LruCache`(及 Support/AndroidX 兼容版)实现强引用最近最少使用(LRU)缓存:先以 `Runtime.getRuntime().maxMemory() / 1024` 获取进程可用堆(KB)并取 `1/8` 作为缓存容量上限,再重写 `sizeOf(key, bitmap)` 返回每张位图的实际内存 KB 数(`getRowBytes() * getHeight() / 1024`,注意默认实现仅返回条目数 `1`),配合 `put`、`get`、`remove` 与 `evictAll` 精确控管内存并在超限时自动淘汰最久未访问条目(在 `entryRemoved` 中可联动磁盘二级缓存)。本站离线实验验证了 `build.prop` 阈值判断、2048×1536 编码内存减半、两步采样缩减 16 倍及 `LruCache` 访问提权与淘汰顺序。

验证堆内存上限、ARGB_8888/RGB_565 字节对比、inSampleSize 2次幂降采样与 LruCache 淘汰

python · 阅读源码
"""Offline verification lab for Android Ch 109: tutorial-bitmap2."""
import json
from collections import OrderedDict

VERSION = "CPython 3.12.14 offline Android socket/graphics/ColorMatrix verifier (Android SDK/emulator absent)"

BUILD_PROP_SNIPPET = """
dalvik.vm.heapstartsize=8m
dalvik.vm.heapgrowthlimit=192m
dalvik.vm.heapsize=512m
dalvik.vm.heaptargetutilization=0.75
dalvik.vm.heapminfree=2m
dalvik.vm.heapmaxfree=8m
"""


def parse_mb(val: str) -> int:
    return int(val.lower().rstrip("m"))


def calc_insamplesize_power_of_two(out_w: int, out_h: int, req_w: int, req_h: int) -> int:
    sample = 1
    if out_h > req_h or out_w > req_w:
        half_h = out_h // 2
        half_w = out_w // 2
        while (half_h // sample) >= req_h and (half_w // sample) >= req_w:
            sample *= 2
    return sample


def calc_insamplesize_source_round(out_w: int, out_h: int, req_w: int, req_h: int) -> int:
    sample = 1
    if out_w > req_w or out_h > req_h:
        wr = round(out_w / req_w)
        hr = round(out_h / req_h)
        sample = max(wr, hr)
    return sample


class LruBitmapCache:
    def __init__(self, max_size_kb: int):
        self.max_size = max_size_kb
        self._store = OrderedDict()
        self.current_size = 0
        self.evicted = []

    def put(self, key: str, size_kb: int):
        if key in self._store:
            self.current_size -= self._store.pop(key)
        self._store[key] = size_kb
        self.current_size += size_kb
        self._trim()

    def get(self, key: str):
        if key not in self._store:
            return None
        self._store.move_to_end(key)
        return self._store[key]

    def remove(self, key: str):
        if key in self._store:
            self.current_size -= self._store.pop(key)

    def evict_all(self):
        self._store.clear()
        self.current_size = 0

    def _trim(self):
        while self.current_size > self.max_size and self._store:
            k, sz = self._store.popitem(last=False)
            self.current_size -= sz
            self.evicted.append(k)


def case_dalvik_art_heap_properties_and_oom_threshold():
    props = {}
    for line in BUILD_PROP_SNIPPET.strip().splitlines():
        k, v = line.split("=", 1)
        props[k.strip()] = v.strip()
    growth_mb = parse_mb(props["dalvik.vm.heapgrowthlimit"])
    large_mb = parse_mb(props["dalvik.vm.heapsize"])
    start_mb = parse_mb(props["dalvik.vm.heapstartsize"])
    oom_standard = (180 + 24) > growth_mb
    fits_large_heap = (180 + 24) <= large_mb
    actual = {
        "heapstartsize_mb": start_mb,
        "heapgrowthlimit_mb": growth_mb,
        "heapsize_large_mb": large_mb,
        "triggers_oom_on_standard_heap": oom_standard,
        "fits_with_largeHeap": fits_large_heap,
    }
    expected = {
        "heapstartsize_mb": 8,
        "heapgrowthlimit_mb": 192,
        "heapsize_large_mb": 512,
        "triggers_oom_on_standard_heap": True,
        "fits_with_largeHeap": True,
    }
    return {
        "name": "dalvik_art_heap_properties_and_oom_threshold",
        "summary": "Verify /system/build.prop heap properties and per-app OOM threshold vs largeHeap",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_pixel_config_memory_comparison():
    w, h = 2048, 1536
    argb8888 = w * h * 4
    rgb565 = w * h * 2
    argb4444 = w * h * 2
    actual = {
        "argb8888_bytes": argb8888,
        "rgb565_bytes": rgb565,
        "argb4444_bytes": argb4444,
        "memory_reduction_pct": round((1 - rgb565 / argb8888) * 100, 1),
    }
    expected = {
        "argb8888_bytes": 12582912,
        "rgb565_bytes": 6291456,
        "argb4444_bytes": 6291456,
        "memory_reduction_pct": 50.0,
    }
    return {
        "name": "pixel_config_memory_comparison",
        "summary": "Verify ARGB_8888 (4 B/px) vs RGB_565/ARGB_4444 (2 B/px) decoded Bitmap memory",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_injustdecodebounds_and_insamplesize_downsampling():
    out_w, out_h = 1024, 768
    req_w, req_h = 128, 128
    pass1_alloc_bytes = 0  # inJustDecodeBounds=True allocates no pixel array
    pow2_sample = calc_insamplesize_power_of_two(out_w, out_h, req_w, req_h)
    round_sample = calc_insamplesize_source_round(out_w, out_h, req_w, req_h)
    full_bytes = out_w * out_h * 4
    sampled_bytes_pow2 = (out_w // pow2_sample) * (out_h // pow2_sample) * 4
    actual = {
        "pass1_alloc_bytes": pass1_alloc_bytes,
        "pow2_inSampleSize": pow2_sample,
        "source_round_inSampleSize": round_sample,
        "full_argb8888_bytes": full_bytes,
        "downsampled_pow2_bytes": sampled_bytes_pow2,
        "memory_factor_reduction": full_bytes // sampled_bytes_pow2,
    }
    expected = {
        "pass1_alloc_bytes": 0,
        "pow2_inSampleSize": 4,
        "source_round_inSampleSize": 8,
        "full_argb8888_bytes": 3145728,
        "downsampled_pow2_bytes": 196608,
        "memory_factor_reduction": 16,
    }
    return {
        "name": "injustdecodebounds_and_insamplesize_downsampling",
        "summary": "Verify two-pass inJustDecodeBounds=true and power-of-2 inSampleSize memory downsampling",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lrucache_eviction_and_softreference_behavior():
    max_memory_kb = 192 * 1024  # 196608 KB
    cache_cap_kb = max_memory_kb // 8  # 24576 KB
    cache = LruBitmapCache(max_size_kb=1000)
    # Each 256x256 ARGB_8888 bitmap = 256*4*256 // 1024 = 256 KB
    img_kb = (256 * 4 * 256) // 1024
    cache.put("img1", img_kb)
    cache.put("img2", img_kb)
    cache.put("img3", img_kb)
    # Touch img1 so img2 becomes least recently used
    hit = cache.get("img1")
    cache.put("img4", img_kb)  # 1024 > 1000 -> evicts img2
    remaining_after_evict = list(cache._store.keys())
    cache.remove("img3")
    size_after_remove = cache.current_size
    cache.evict_all()
    actual = {
        "one_eighth_of_192mb_kb": cache_cap_kb,
        "img_256x256_kb": img_kb,
        "hit_img1_kb": hit,
        "evicted_keys": cache.evicted,
        "remaining_after_evict": remaining_after_evict,
        "size_after_remove_kb": size_after_remove,
        "size_after_evict_all": cache.current_size,
    }
    expected = {
        "one_eighth_of_192mb_kb": 24576,
        "img_256x256_kb": 256,
        "hit_img1_kb": 256,
        "evicted_keys": ["img2"],
        "remaining_after_evict": ["img3", "img1", "img4"],
        "size_after_remove_kb": 512,
        "size_after_evict_all": 0,
    }
    return {
        "name": "lrucache_eviction_and_softreference_behavior",
        "summary": "Verify LruCache 1/8 maxMemory sizing, sizeOf KB math, LRU eviction, remove, and evictAll",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_dalvik_art_heap_properties_and_oom_threshold(),
        case_pixel_config_memory_comparison(),
        case_injustdecodebounds_and_insamplesize_downsampling(),
        case_lrucache_eviction_and_softreference_behavior(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 192MB 堆上限、2048x1536 减半至 6MiB、1024x768 采样 4 倍省 16 倍内存及 LruCache 1000KB 容量下淘汰 img2。
验证堆内存上限、ARGB_8888/RGB_565 字节对比、inSampleSize 2次幂降采样与 LruCache 淘汰

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:2245b0c790e3b443eb99063a291e38f1b608b5857a449d613e6c0468cd3de414

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载8.2.2 Bitmap 引起的 OOM 问题实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:e98b03f46ea01447c56d2295ace2190706b2c6acb94b2a0b01d9607870a32779

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么重写 LruCache 的 sizeOf(String key, Bitmap value) 时不能保留默认返回 1 的实现?

展开参考解答

默认 sizeOf 返回 1 时 LruCache 只能按缓存图片张数限流,而不同分辨率位图内存相差悬殊;重写为返回位图所占 KB 数才能按真实内存容量上限精确淘汰,防止单批大图引发 OOM。

规范与官方依据