Android应用徽章计数递增方法及无支持设备替代方案咨询
ShortcutBadger 相关问题解答
1. 如何获取当前徽章计数实现递增
ShortcutBadger 库本身没有提供读取当前图标徽章计数的API,你需要自己在本地维护这个计数,比如用SharedPreferences存储:
实现逻辑及代码:
- 初始化时从本地读取已保存的计数,无记录则默认设为0
- 递增时取出当前计数加1,调用ShortcutBadger更新徽章后,将新计数存回本地
// 获取SharedPreferences实例 val sp = getSharedPreferences("BadgeCountPrefs", MODE_PRIVATE) // 读取当前计数,默认值为0 var currentCount = sp.getInt("badge_count", 0) // 计数递增 currentCount += 1 try { ShortcutBadger.applyCountOrThrow(this, currentCount) Log.d("ShortcutBadger Success:", currentCount.toString()) // 保存更新后的计数 sp.edit().putInt("badge_count", currentCount).apply() } catch (e: ShortcutBadgeException) { Log.d("ShortcutBadger Fail:", e.toString()) }
2. 用通知点替代图标徽章
完全可以。对于不支持ShortcutBadger的设备,Android 8.0(API 26)及以上版本提供了原生**通知点(Notification Badge)**特性,会自动在应用图标上显示对应通知的计数,可作为替代方案。
实现逻辑及代码:
- 先创建通知渠道(API 26+强制要求)
- 发送带有
number属性的通知,系统会自动同步显示计数
// 1. 创建通知渠道(仅需调用一次) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelId = "badge_notification_channel" val channelName = "Badge Notification" val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(true) // 开启通知点显示 } val notificationManager = getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(channel) } // 2. 发送带计数的通知 val notificationId = 1 val badgeCount = 3 // 要显示的计数数字 val notification = NotificationCompat.Builder(this, "badge_notification_channel") .setSmallIcon(R.drawable.ic_notification) // 必须设置通知图标 .setContentTitle("通知标题") .setContentText("通知内容") .setNumber(badgeCount) // 设置通知点的计数 .setPriority(NotificationCompat.PRIORITY_LOW) .build() val notificationManager = NotificationManagerCompat.from(this) notificationManager.notify(notificationId, notification)
提示:若要清除通知点,取消对应ID的通知即可。
内容的提问来源于stack exchange,提问作者shinyatk
相关产品推荐
相关产品推荐

