【发布时间】:2019-12-18 10:55:25
【问题描述】:
我正在尝试创建一个每分钟检查设备位置的前台服务,并且我已经设法使其工作。但是关于服务处于活动状态的强制性通知,我有一些问题。
我无法让通知徽章停止显示,也无法以编程方式最小化通知。
以下是相关部分:
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)。
我错过了什么?
【问题讨论】:
-
不是真的,我昨天尝试了答案中描述的内容,但没有运气当我设置
IMPORTANCE_MIN时,调试器说通道重要性 = 1,这是正确的。当我手动更改设置时,它表示重要性 = 2,即IMPORTANCE_LOW。当我以编程方式设置为 LOW 时,它表示重要性 = 2,但行为与重要性 = 1 时的行为相同,因此它必须是其他东西。编辑:我可能把某事误认为某事,但归根结底,文档说前台服务应该使用IMPORTANCE_LOW,但它的行为与其他服务不同。 -
您能否附上一张图片,说明您所说的“它的行为与其他服务不同”
-
@greeble31 pasteboard.co/ILY7llK.png Unpause 是我的应用,我希望通知类似于它下方的 Google 天气通知
标签: android push-notification foreground-service