目前我有这个WET代码,因为NotificationCompat不支持setSmallIcon用于Icon而不是resource-id:
val notification = if (Build.VERSION.SDK_INT < 23) {
NotificationCompat.Builder(this)
.setLargeIcon(bitmap)
.setSmallIcon(R.drawable.ic_launcher)
.setContentText(intentDescriber!!.userFacingIntentDescription)
.setContentTitle(label)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build()
} else {
Notification.Builder(this)
.setSmallIcon(Icon.createWithBitmap(bitmap))
.setLargeIcon(bitmap)
.setContentText(intentDescriber!!.userFacingIntentDescription)
.setContentTitle(label)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build()
}
有没有办法让这个更好(DRY?) - 问题是两个构建器类都不同......
答案 0 :(得分:0)
如果您习惯使用反射,那么不要在构建器中设置小图标,而是在构建的通知中设置它。您可以在那里查看SDK 23,并使用反射调用setSmallIcon(它是一个公共方法,但是被隐藏。我怀疑它会改变),否则在通知中设置图标字段。
答案 1 :(得分:0)
缺乏反思我建议使用两个实现创建自己的构建器界面:一个用于NotificationCompat.Builder
,另一个用于Notification.Builder
。你可能会重复&#34; android&#34;但你不会重复自己。 e.g:
interface NotificationFacadeBuilder<out T> {
/* facade builder method declarations go here */
fun build(): T
}
class SupportAppNotificationCompatFacadeBuilder(context: Context)
: NotificationFacadeBuilder<NotificationCompat> {
val builder = NotificationCompat.Builder(context)
/* facade builder method implementations go here and delegate to `builder` */
override fun build(): NotificationCompat = TODO()
}
class AppNotificationFacadeBuilder(context: Context)
: NotificationFacadeBuilder<Notification> {
val builder = Notification.Builder(context)
/* facade builder method implementations go here and delegate to `builder` */
override fun build(): Notification = TODO()
}
NotificationFacadeBuilder
(或者你决定称之为的任何东西)必须声明你需要的每个公共构建器方法,然后每个实现类将简单地委托给它们各自的实际构建器实现。