"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-bitmap2-lab/explore-tutorial-bitmap2.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-bitmap2.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1847.zip
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip