[英]How can I use vectorDrawable as icon for push notifications using Android Support Library 23.2? setSmallIcon gives error
[英]Can we use VectorDrawable or VectorXML as icons for push notifications in android?
我使用的是 PNG 圖像,但它的尺寸變得太大了,所以我不得不妥協它的質量。 所以我在想向量可能是另一種方式? 示例將是一個很大的幫助。
VectorDrawables 將僅用作高於(或等於)Android Lollipop 版本的通知圖標 - 即 API 21。
我知道這一點,因為我確實嘗試使用.setSmallIcon(R.drawable.my_vector)
,如此處的其他答案之一所示,盡管這對於 API 21 及更高版本非常有效,但對於 Lollipop 之前的版本,我收到以下錯誤:
android.app.RemoteServiceException:從包 com.example.app 發布的錯誤通知:無法創建圖標:StatusBarIcon(pkg=com.example.appuser=0 id=0x7f02005a level=0 visible=true num=0 )
Stack Overflow 上還有其他答案支持這個論點:
我們可以使用 VectorDrawable 或 VectorXML 作為推送通知的圖標嗎?
是的,只需將 vector drawable 稱為通知的標准方式:
.setSmallIcon(R.drawable.my_vector)
為了使用透明度(通知圖標只有白色和/或透明),在矢量 XML 中設置顏色時必須使用 alpha 通道,這意味着 #00000000 表示透明,#FFFFFFFF 表示白色。
對於版本 < 21,
如果您想直接將矢量可繪制資源 id 傳入setSmallIcon() : 沒辦法。
對於setLargeIcon()間接,是的。 用
VectorDrawableCompat drawable = VectorDrawableCompat.create(context.getResources(), resource id, theme);
然后從這個 drawable 創建 Bitmap 並傳遞給setLargeIcon()
如果您堅持使用 Vector drawable 嘗試將其轉換為bitmap :
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.my_vector_drawable);
mBuilder = new NotificationCompat.Builder(context)
.setLargeIcon(bitmap)
.setOngoing(!cancelable);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(getNotificationIcon());
}
您可以使用 Firebase 通知執行以下操作
在清單上添加這些:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_http" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/notification_color" />
最進口的東西!
如果您使用矢量可繪制支持包,您可能不應該在通知中使用 VectorDrawable 圖標 - 您可能會在棒棒糖之前的設備上遇到錯誤。
看看這個: Notification throws error when using vector drawables
沒有矢量可繪制支持包,我沒有遇到任何錯誤,但使用它后,pre-lollipop 設備在通知時無法訪問矢量圖標並拋出此錯誤:
android.app.RemoteServiceException:從包 com.xxx.xxx 發布的錯誤通知:無法創建圖標:StatusBarIcon(pkg=com.xxx.xxxuser=0 id=0x7f020082 level=0 visible=true num=0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.