[英]Android: Notification builder: alternative to setcolor method for API19
I need to set the color of notification. 我需要设置通知的颜色。 It works fine if minSdk is at least
API Level 21
. 如果minSdk至少为
API Level 21
,则可以正常工作。 Once I drop the minSdk, code (below) doesn't compile. 删除minSdk后,下面的代码将无法编译。
notification = builder.setContentTitle(MyApp.getAppContext().getResources().getString(R.string.notification_content_title))
.setContentText(contentText)
.setColor(color)
.build();
I get the following error message once I downgrade MinSdk to API Level 19
: 将MinSdk降级到
API Level 19
我得到以下错误消息:
Call requires API level 21 (current min is 19): android.app.Notification.Builder#setColor
调用需要API级别21(当前最小值为19):android.app.Notification.Builder#setColor
What would be the workaround? 解决方法是什么? I came across NotificationCompact, should I switch to it?
我遇到了NotificationCompact,我应该切换到它吗?
I would recommend using NotificationCompat.Builder
(from support library) instead of Notification.Builder
. 我建议使用
NotificationCompat.Builder
(来自支持库)而不是Notification.Builder
。
To do so you will need the support v4 library in your project. 为此,您将在项目中需要支持v4库。 If you don't have it already add this line to the dependencies closure of your
build.gradle
file: 如果您还没有,请将此行添加到
build.gradle
文件的依赖项关闭中:
compile "com.android.support:support-v4:23.1.1"
Then you would use NotificationCompat.Builder
to make your notification. 然后,您将使用
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();
Note that NotificationCompat.Builder
cannot not backport all the functionality into older versions of android. 请注意,
NotificationCompat.Builder
无法将所有功能反向移植到旧版本的android中。 Most of it (like the color of the notification) will be ignored in older versions of android. 大部分(如通知的颜色)在旧版android中将被忽略。
NotificationCompat.Builder
will just prevent the errors you are seeing. NotificationCompat.Builder
只会阻止您看到的错误。
Alternatively you could add a SDK check before setting the color, but that would be a more verbose approach to doing what NotificationCompat.Builder
does for you: 另外,您可以在设置颜色之前添加一个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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.