xml – Can we use VectorDrawable or VectorXML as icons for push notifications in android?-ThrowExceptions

Exception or error:

I am using PNG image but its size is getting too big so I have to compromise with its quality. So i was thinking vectors may be the another way around ?
Example will be a great help.

How to solve:

Can we use VectorDrawable or VectorXML as icons for push notifications?

Yes, just call the vector drawable the standard way for notifications:

.setSmallIcon(R.drawable.my_vector)

In order to use the transparency (notification icons are only white and/or transparent), you will have to use the alpha channels when settings the colors in the vector XML, meaning #00000000 for transparent and #FFFFFFFF for white.

###

VectorDrawables will only work as notification icons for versions higher than (or equal to) Android Lollipop – i.e. API 21.

I know this because I did try using .setSmallIcon(R.drawable.my_vector) as shown in one of the other answers here, and although this works perfectly fine for API 21 and above, I got the following error for versions prior to Lollipop:

android.app.RemoteServiceException: Bad notification posted from package com.example.app: Couldn’t create icon: StatusBarIcon(pkg=com.example.appuser=0 id=0x7f02005a level=0 visible=true num=0 )

There are also other answers on Stack Overflow supporting this argument:

###

If you insist to use Vector drawable try converting it to 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());
                    }

###

Probably you should not use VectorDrawable icons in notifications if you are using vector drawable support package – you may encounter errors on pre-lollipop devices.

Check out this: Notification throws error when using vector drawables

Wuthout vector drawable support package, I didn’t encounter any errors but after using it, pre-lollipop devices were unable to access the vector icon at the time of notification and threw this error:

android.app.RemoteServiceException: Bad notification posted from
package com.xxx.xxx: Couldn’t create icon:
StatusBarIcon(pkg=com.xxx.xxxuser=0 id=0x7f020082 level=0 visible=true
num=0)

###

For version < 21,

If you want to directly pass in vector drawable resource id into setSmallIcon(): No way.

For setLargeIcon() indirectly, yes. Use

VectorDrawableCompat drawable = VectorDrawableCompat.create(context.getResources(), resource id, theme);

then create Bitmap from this drawable and pass into setLargeIcon()

Leave a Reply

Your email address will not be published. Required fields are marked *