Search code examples
androidandroid-notificationsandroid-icons

How to find actual size of small notification icon at run time?


I know there's a list of different sizes for small notification icons for different screen DPIs, as shown here. This is useful to know when preparing a set of static icon files for the application.

But I need to create an icon dynamically, using setSmallIcon(Icon) from Notification.Builder. For large icon, I can call e.g. getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width) and similar for height to get exact numeric values. How can I do the same for small icon?


Solution

  • The small icon has a size of 24 dp. You can calculate the actual size in px at runtime.

    Kotlin:

    val smallIconSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, resources.displayMetrics)
    

    Java:

    float smallIconSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics())
    

    If you don't have a context (to use getResources), you can use this as fallback:

    val smallIconSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, Resources.getSystem().displayMetrics)