Я создаю приложение таймера с несколькими инструментами. На таймере я хочу показать секунду или время в строке состояния. На данный момент я следую приведенному ниже подходу, < /p>
Преобразовать текст в растровый карту < /li>
Затем преобразовать растровый карту в икону < /li>
Покажите, что значок на Br /br /> < /ol>
ниже, < /p>
ниже.override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestNotificationPermission()
// Example: show "14" in the notification icon
displayNotification("5F")
}
< /code>
private fun displayNotification(text: String) {
// Create notification channel for O+
createNotificationChannelIfNeeded()
// Step 1: convert text -> bitmap
val bitmap = createBitmapFromString(text.trim())
// Step 2 & 3: create Icon from bitmap and attach to Notification.Builder
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
Notification.Builder(this)
}
// set the small icon using the Icon created from bitmap (API 23+)
builder.setSmallIcon(Icon.createWithBitmap(bitmap))
.setContentTitle("Simple Notification")
.setContentText("This is a simple notification showing \"$text\"")
.setAutoCancel(true)
// set priority for pre-O devices (channel controls priority for O+)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
builder.setPriority(Notification.PRIORITY_MAX)
}
// Post the notification
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(NOTIFICATION_ID, builder.build())
}
< /code>
private fun createNotificationChannelIfNeeded() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Custom Number Notifications"
val desc = "Channel for notifications that use a bitmap small icon"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance)
channel.description = desc
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.createNotificationChannel(channel)
}
}
< /code>
private fun createBitmapFromString(text: String): Bitmap {
// Use dp -> px to create a reasonably sized bitmap that will scale well on different densities
val density = resources.displayMetrics.density
val sizeDp = 24f // target ~24dp icon size (system will scale it)
val sizePx = (sizeDp * density).toInt().coerceAtLeast(24)
val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
// Optional: draw a subtle circle background for visibility (comment out if you want plain text)
val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.TRANSPARENT // keep transparent background for better system tinting
style = Paint.Style.FILL
}
canvas.drawCircle(sizePx / 2f, sizePx / 2f, sizePx / 2.5f, bgPaint)
// Text paint - white and bold (status bar usually expects monochrome icons)
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
textSize = sizePx * 0.6f
textAlign = Paint.Align.CENTER
}
// Center text vertically
val bounds = Rect()
textPaint.getTextBounds(text, 0, text.length, bounds)
val x = sizePx / 2f
val y = sizePx / 2f - bounds.exactCenterY()
canvas.drawText(text, x, y, textPaint)
return bitmap
}
< /code>
Now this is working, but my timer will update every single second, and I feel that this isn't the best approach I should take.
Are there any other ways to get dynamic text in the notification status?
Подробнее здесь: https://stackoverflow.com/questions/797 ... in-android
Как показать динамическое число в строке состояния уведомления в Android? ⇐ Android
Форум для тех, кто программирует под Android
1755139941
Anonymous
Я создаю приложение таймера с несколькими инструментами. На таймере я хочу показать секунду или время в строке состояния. На данный момент я следую приведенному ниже подходу, < /p>
Преобразовать текст в растровый карту < /li>
Затем преобразовать растровый карту в икону < /li>
Покажите, что значок на Br /br /> < /ol>
ниже, < /p>
ниже.override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestNotificationPermission()
// Example: show "14" in the notification icon
displayNotification("5F")
}
< /code>
private fun displayNotification(text: String) {
// Create notification channel for O+
createNotificationChannelIfNeeded()
// Step 1: convert text -> bitmap
val bitmap = createBitmapFromString(text.trim())
// Step 2 & 3: create Icon from bitmap and attach to Notification.Builder
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, CHANNEL_ID)
} else {
Notification.Builder(this)
}
// set the small icon using the Icon created from bitmap (API 23+)
builder.setSmallIcon(Icon.createWithBitmap(bitmap))
.setContentTitle("Simple Notification")
.setContentText("This is a simple notification showing \"$text\"")
.setAutoCancel(true)
// set priority for pre-O devices (channel controls priority for O+)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
builder.setPriority(Notification.PRIORITY_MAX)
}
// Post the notification
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(NOTIFICATION_ID, builder.build())
}
< /code>
private fun createNotificationChannelIfNeeded() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Custom Number Notifications"
val desc = "Channel for notifications that use a bitmap small icon"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance)
channel.description = desc
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.createNotificationChannel(channel)
}
}
< /code>
private fun createBitmapFromString(text: String): Bitmap {
// Use dp -> px to create a reasonably sized bitmap that will scale well on different densities
val density = resources.displayMetrics.density
val sizeDp = 24f // target ~24dp icon size (system will scale it)
val sizePx = (sizeDp * density).toInt().coerceAtLeast(24)
val bitmap = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
// Optional: draw a subtle circle background for visibility (comment out if you want plain text)
val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.TRANSPARENT // keep transparent background for better system tinting
style = Paint.Style.FILL
}
canvas.drawCircle(sizePx / 2f, sizePx / 2f, sizePx / 2.5f, bgPaint)
// Text paint - white and bold (status bar usually expects monochrome icons)
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
textSize = sizePx * 0.6f
textAlign = Paint.Align.CENTER
}
// Center text vertically
val bounds = Rect()
textPaint.getTextBounds(text, 0, text.length, bounds)
val x = sizePx / 2f
val y = sizePx / 2f - bounds.exactCenterY()
canvas.drawText(text, x, y, textPaint)
return bitmap
}
< /code>
Now this is working, but my timer will update every single second, and I feel that this isn't the best approach I should take.
Are there any other ways to get dynamic text in the notification status?
Подробнее здесь: [url]https://stackoverflow.com/questions/79734512/how-do-i-show-a-dynamic-number-in-notification-status-bar-in-android[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия