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
相关产品推荐
相关产品推荐

