Как показать динамическое число в строке состояния уведомления в Android?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как показать динамическое число в строке состояния уведомления в Android?

Сообщение 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?

Подробнее здесь: https://stackoverflow.com/questions/797 ... in-android
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»