Android:通知构建器:API19的setcolor方法的替代方案

时间:2016-07-22 02:46:53

标签: android android-notifications

我需要设置通知的颜色。如果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后,我收到以下错误消息:

  

调用需要API级别21(当前最小值为19):android.app.Notification.Builder #setColor

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

1 个答案:

答案 0 :(得分:0)

我建议使用NotificationCompat.Builder(来自支持库)而不是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();