我有一个应用程序显示自定义通知。问题是在Android 5中运行时,通知栏中的小图标显示为白色。我该如何解决这个问题?


当前回答

供您参考:如果图标没有出现,请确保您的本地或远程通知配置包含正确的图标名称

'largeIcon' => 'ic_launcher',
'smallIcon' => 'ic_launcher' // defaults to ic_launcher, 

其他回答

alpha-channel是Android用于通知图标的图像的唯一数据:

Alpha == 1:像素显示为白色 alpha == 0:像素显示为您选择的Notification.Builder#setColor(int)

https://developer.android.com/about/versions/android-5.0-changes.html上提到了这一点:

系统会忽略操作图标和主通知图标中的所有非alpha通道。您应该假设这些图标都是纯alpha的。

几乎所有的内置绘图似乎都适合alpha图像,所以你可能会使用类似的东西:

Notification.Builder.setColor(Color.RED)
                    .setSmallIcon(android.R.drawable.star_on)

但我仍在寻找官方证实这一点的API文档。

在Android 22上测试。

这是Android用来显示通知图标的代码:

// android_frameworks_base/packages/SystemUI/src/com/android/systemui/
//   statusbar/BaseStatusBar.java

if (entry.targetSdk >= Build.VERSION_CODES.LOLLIPOP) {
    entry.icon.setColorFilter(mContext.getResources().getColor(android.R.color.white));
} else {
    entry.icon.setColorFilter(null);
}

所以你需要将目标sdk版本设置为<21,图标将保持颜色。这是一个丑陋的解决方案,但它做到了预期的效果。无论如何,我真的建议遵循谷歌的设计准则:“通知图标必须完全是白色的。”

下面是你如何实现它:

如果你使用Gradle/Android Studio来构建应用,请使用build. Gradle:

defaultConfig {
    targetSdkVersion 20
}

否则(Eclipse等)使用AndroidManifest.xml:

<uses-sdk android:minSdkVersion="..." android:targetSdkVersion="20" />

完全同意用户Daniel Saidi的观点。为了有颜色的NotificationIcon,我写这个答案。

为此,你必须创建像剪影这样的图标,并使某些部分透明,无论你想添加颜色的地方。也就是说,

你可以使用

.setColor (your_color_resource_here)

注意:setColor只在Lollipop中可用,所以,你必须检查OSVersion

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    Notification notification = new Notification.Builder(context)
    ...
} else {
    // Lollipop specific setColor method goes here.
    Notification notification = new Notification.Builder(context)
    ...
    notification.setColor(your_color)
    ...            
}

您也可以使用Lollipop作为目标SDK来实现这一点。

关于NotificationIcon的所有说明均在谷歌开发人员控制台通知指南行中给出。

首选通知图标大小24x24dp

mdpi    @ 24.00dp   = 24.00px
hdpi    @ 24.00dp   = 36.00px
xhdpi   @ 24.00dp   = 48.00px

更多信息请参考通知图标大小的链接。

另一种选择是利用特定于版本的可绘制(mipmap)目录为Lollipop和以上版本提供不同的图形。

在我的应用程序中,“v21”目录包含带有透明文本的图标,而其他目录包含非透明版本(适用于比棒棒糖更老的Android版本)。

它应该是这样的:

这样,你就不需要检查代码中的版本号,例如:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_notification)
        .setContentTitle(title)
        .setContentText(message)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

同样,如果您使用“icon”属性,则可以在GCM有效负载中引用“ic_notification”(或您选择的任何名称)。

https://developers.google.com/cloud-messaging/http-server-ref#notification-payload-support

从manifest.xml中删除android:targetSdkVersion="21"它会起作用的! 从这一点上看,在你的apk中没有任何问题,这只是一个技巧,我应用这个,我在通知中发现了彩色图标