Last active
July 18, 2023 13:40
-
-
Save ferdy182/5223f7e8eeb36c77ebefdb5b02e4fbfe to your computer and use it in GitHub Desktop.
Create an android notification that contains the current time in the icon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun postCounter() { | |
val currentTime = LocalTime.now() | |
val formattedTime = currentTime.format(DateTimeFormatter.ofPattern("HH:mm")) | |
val icon = IconCompat.createWithBitmap( | |
textAsBitmap( | |
text = formattedTime, | |
textSize = 14f, | |
textColor = getCurrentThemeAttributeColor(R.attr.colorNextPrimary, context.theme) | |
) | |
) | |
val n = NotificationCompat.Builder(context, CHANNEL_ID_HIGH).apply { | |
setSmallIcon(icon) | |
setContentText(formattedTime) | |
}.build() | |
NotificationManagerCompat.from(context).notify(timeId, n) | |
} | |
private fun getCurrentThemeAttributeColor(attributeId: Int, theme: Theme): Int { | |
val typedValue = TypedValue() | |
val resolved = theme.resolveAttribute(attributeId, typedValue, true) | |
return if (resolved) { | |
typedValue.data | |
} else { | |
// Return a default color if the attribute couldn't be resolved | |
// or if the theme doesn't contain the specified attribute | |
// (e.g., if it's a custom attribute) | |
// You can return any default color you prefer. | |
// For example, Color.RED or Color.parseColor("#FF0000") | |
// This example returns Color.BLACK as a fallback color. | |
android.graphics.Color.BLACK | |
} | |
} | |
private fun textAsBitmap(text: String?, textSize: Float, textColor: Int): Bitmap { | |
val paint = Paint(Paint.ANTI_ALIAS_FLAG) | |
paint.textSize = textSize | |
paint.color = textColor | |
paint.textAlign = Paint.Align.LEFT | |
val baseline = -paint.ascent() // ascent() is negative | |
val width = (paint.measureText(text) + 0.5f).toInt() // round | |
val height = (baseline + paint.descent() + 0.5f).toInt() | |
val image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) | |
val canvas = Canvas(image) | |
canvas.drawText(text!!, 0f, baseline, paint) | |
return image | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment