You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose适配图标加载异常:Android 8.1设备崩溃排查

问题:Jetpack Compose加载启动图标在Android 8.1真机崩溃原因

我在Jetpack Compose中使用自定义的adaptiveIconPainterResource函数加载应用启动图标,该函数在Android 6、12-14真机及Android 8.1模拟器上运行正常,但Firebase Crashlytics显示部分Android 8.1真机出现崩溃。

崩溃信息:

ResourcesCompat.getDrawable无法将资源转为AdaptiveIconDrawable,转而调用painterResource时触发异常:“Only VectorDrawables and rasterized asset types are supported ex. PNG, JPG, WEBP”

当前使用Android Studio生成的webp格式mipmap资源,Android 6设备可正常运行,改用Glide Compose库加载后问题解决,想知道崩溃的具体原因。

相关代码

展示图标代码

Image(
    modifier = Modifier.size(24.dp),
    painter = adaptiveIconPainterResource(id = R.mipmap.ic_launcher_round),
    contentDescription = stringResource(id = R.string.app_name),
)

adaptiveIconPainterResource函数

@Composable
fun adaptiveIconPainterResource(@DrawableRes id: Int): Painter {
    val context = LocalContext.current
    val res = context.resources
    val theme = context.theme

    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Android O supports adaptive icons, try loading this first (even though this is least likely to be the format).
        val adaptiveIcon = remember(id) {
            ResourcesCompat.getDrawable(res, id, theme) as? AdaptiveIconDrawable
        }
        if (adaptiveIcon != null) {
            remember(id) {
                BitmapPainter(adaptiveIcon.toBitmap().asImageBitmap())
            }
        } else {
            // We couldn't load the drawable as an Adaptive Icon, just use painterResource
            painterResource(id)
        }
    } else {
        // We're not on Android O or later, just use painterResource
        painterResource(id)
    }
}

Glide Compose替代代码

GlideImage(
    modifier = Modifier.size(24.dp),
    model = R.mipmap.ic_launcher_round,
    transition = CrossFade,
    contentDescription = stringResource(id = R.string.app_name),
)

崩溃原因分析

  • 厂商定制系统的Drawable封装差异:Android 8.1(API 27)虽属于Android O及以上版本,但部分厂商定制系统会对启动图标资源做额外封装,导致ResourcesCompat.getDrawable返回的Drawable既不是AdaptiveIconDrawable,也不是Compose的painterResource支持的VectorDrawable、WebP、PNG等类型(比如厂商自定义的LauncherIconDrawable),调用painterResource时直接触发类型不支持的异常。
  • 模拟器与真机的资源逻辑不同:Android 8.1模拟器使用原生系统逻辑,加载启动图标时返回标准的Drawable类型;但定制化真机的资源加载逻辑被修改,无法返回painterResource可识别的Drawable类型。
  • Glide的适配能力:Glide Compose内部对各类Drawable做了全面的适配处理,能自动解析厂商包装后的Drawable并转换为Compose可识别的格式,因此不会触发异常。

内容的提问来源于stack exchange,提问作者user924

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:42:48