There are several icons you can set on an Android notification: small app icon and a large optional icon for the body of the notification.
In this post we will explore how to set a large vector graphics icon on an Android Notification.
Check out the notification anatomy for more details.
Here’s an example of how an XML file with vector image of three dots might look.
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FF000000" android:pathData="..."/> </vector>
Place this XML file under the folder res -> drawable in your project.
Read more about vector drawable resources and how to create them.
You will need a Bitmap file in order to set a large icon for your Android notification.
Vector XML files are of type Drawable and not Bitmap and need to be converted to Bitmap.
Normally with PNG and JPG files you would use BitmapFactory.decodeResource() to set the resource as an icon. In case of vector files it will return null for shapes defined in xml drawable files.
Here’s how to convert vector graphics image to a bitmap in Android.
First, get a Drawable object from your vector file:
Drawable largeIcon = getResources().getDrawable(R.drawable.more);
Second, convert the drawable to bitmap using Canvas:
public static Bitmap drawableToBitmap (Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable)drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; }
If you get exceptions like IllegalArgumentException: width and height must be > 0
make sure you set the right dimensions in your vector file (we set 24dp for height and width).
First, create the Android notification and set all required parameters:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); mBuilder.setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(largeIcon) .setColor(ContextCompat.getColor(context, R.color.yellow)) .setContentTitle("My notification") .setContentText("Here comes some text") .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true) .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Small icon and large icon are different things! Small icon is a main App icon and is required. Large icon is an optional icon and is used to make the notification more personal or give it more information.
In our example we have also provided several extra options:
setAutoCancel(true)
,setVibrate()
setSound()