Android:通知生成器:API19 的 setcolor 方法的替代方法

Android: Notification builder: alternative to setcolor method for API19

我需要设置通知的颜色。如果 minSdk 至少为 API Level 21,它工作正常。删除 minSdk 后,代码(下方)无法编译。

notification = builder.setContentTitle(MyApp.getAppContext().getResources().getString(R.string.notification_content_title))
                .setContentText(contentText)
                .setColor(color)
                .build();

将 MinSdk 降级到 API Level 19 后,我收到以下错误消息:

Call requires API level 21 (current min is 19): android.app.Notification.Builder#setColor

解决方法是什么?我遇到了 NotificationCompact,我应该切换到它吗?

我建议使用 NotificationCompat.Builder (from support library) instead of Notification.Builder

为此,您的项目中需要支持 v4 库。如果您还没有将此行添加到 build.gradle 文件的依赖项闭包中:

compile "com.android.support:support-v4:23.1.1"

然后您将使用 NotificationCompat.Builder 发出通知。

String title = MyApp.getAppContext().getResources()
                                   .getString(R.string.notification_content_title);
Notification notification = new NotificationCompat.Builder(context)
                 .setContentTitle(title)
                 .setContentText(contentText)
                 .setColor(color)
                 .build();

请注意,NotificationCompat.Builder 无法将所有功能反向移植到 android 的旧版本中。在旧版本 android 中,大部分内容(如通知的颜色)将被忽略。 NotificationCompat.Builder 只会防止您看到的错误。

或者,您可以在设置颜色之前添加一个 SDK 检查,但这将是一种更冗长的方法来执行 NotificationCompat.Builder 为您所做的事情:

String title = MyApp.getAppContext().getResources().getString(R.string.notification_content_title);
Notification.Builder builder = new Notification.Builder(context)
                 .setContentTitle(title)
                 .setContentText(contentText);
if (Build.VERSION.SDK_INT >= ApiHelper.VERSION_CODES.LOLLIPOP) {
  builder.setColor(color);
}
Notification notification = builder.build();