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

Jetpack Compose设置通知大图标出现类型不匹配错误如何解决

错误原因

NotificationCompat.Builder的setLargeIcon()方法要求传入Bitmap类型的实例,你直接传了R.drawable.header,这是Android系统生成的drawable资源唯一标识,属于Int类型,所以触发类型不匹配报错。

修复方案

你需要先把drawable资源转换为Bitmap对象,再传入setLargeIcon()方法,针对你使用png格式图片的场景,直接用系统自带的BitmapFactory解码资源即可:

@Composable
fun NotificationApp() {
    val context = LocalContext.current
    val channelId = "MyTestChannel"
    val notificationId = 0

    // 新增:将drawable资源转换为Bitmap
    val largeIcon = BitmapFactory.decodeResource(context.resources, R.drawable.header)

    val builder = NotificationCompat.Builder(context, channelId)
        .setSmallIcon(R.drawable.ic_edit_location) 
        .setContentTitle("My Test Notification")
        .setContentText("This is my test notification in one line...")
        .setLargeIcon(largeIcon) // 替换为转换后的Bitmap对象
        .setStyle(
            NotificationCompat.BigTextStyle()
                .bigText(
                    "This is my test notification in one line. Made it longer " +
                            "by setting the setStyle property. " +
                            "It should not fit in one line anymore, " +
                            "rather show as a longer notification content."
                )
        )
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    createNotificationChannel(channelId, context)

    with(NotificationManagerCompat.from(context)) {
        notify(notificationId, builder.build())
    }
}

如果你后续需要使用矢量图作为大图标,可以使用下面的通用转换方法处理:

fun drawableToBitmap(drawable: Drawable): Bitmap {
    if (drawable is BitmapDrawable) {
        return drawable.bitmap
    }
    val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    drawable.setBounds(0, 0, canvas.width, canvas.height)
    drawable.draw(canvas)
    return bitmap
}

调用方式如下:

val drawable = ContextCompat.getDrawable(context, R.drawable.header) ?: return
val largeIcon = drawableToBitmap(drawable)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:18:04