我正在尝试创建一个前台服务,该服务每分钟检查一次设备位置,并且设法使其正常运行。但是,关于强制性通知该服务处于活动状态,我有一些问题。
我无法获得停止显示的通知徽章,也无法以编程方式将通知最小化。
以下是相关部分:
class LocationPollingService : Service() {
companion object {
const val NOTIF_ID = 2
const val NOTIF_CHANNEL_ID = "background_service_notification"
const val NOTIF_CHANNEL_NAME = "Background service"
}
@Nullable
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(
intent: Intent?,
flags: Int,
startId: Int
): Int {
createBackgroundNotifChannel()
startForeground()
requestLocation()
return super.onStartCommand(intent, flags, startId)
}
private fun startForeground() {
val notificationIntent = Intent(this, SplashActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this, 0,
notificationIntent, 0
)
val notification = NotificationCompat.Builder(
this,
NOTIF_CHANNEL_ID
)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_app_icon)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.im_watching_you))
.setContentIntent(pendingIntent)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(NOTIF_ID, notification.build())
} else {
notification.priority = NotificationCompat.PRIORITY_MIN
startForeground(NOTIF_ID, notification.build())
}
}
private fun createBackgroundNotifChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelBackground = NotificationChannel(
NOTIF_CHANNEL_ID,
NOTIF_CHANNEL_NAME,
NotificationManager.IMPORTANCE_LOW
).apply {
description = getString(
R.string.notification_channel_background_description
)
enableLights(false)
enableVibration(false)
setShowBadge(false)
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channelBackground)
}
}
}
如果我理解正确,应该IMPORTANCE_LOW
用于此类通知,并且默认情况下应将其最小化。通知永远不会最小化,我也不能通过单击最小化。使它最小化的唯一方法是手动更改设备设置中的通知通道设置(将Notification style
设置为Silent and minimized
,而不仅仅是默认的silent
)。我尝试将重要性设置为IMPORTANCE_MIN
和IMPORTANCE_NONE
,但这并没有改变。
如上所述,第二个问题是尽管显示了setShowBadge(false)
,但仍然显示了徽章(通知计数器显示在应用程序图标上)。
我想念什么?
答案 0 :(得分:-2)
您需要在生成通知后通知通知,如下所示:
notificationManager.notify(NOTIF_ID,notification.build());
答案 1 :(得分:-2)
用于从状态栏隐藏通知徽章 您应该更改通知渠道的优先级:
val channelBackground = NotificationChannel( NOTIF_CHANNEL_ID, NOTIF_CHANNEL_NAME, NotificationManager.IMPORTANCE_MIN