【发布时间】:2021-06-28 07:20:07
【问题描述】:
需要使前台服务显示的通知静音。为了使通知静音,我使用了许多 SO 建议的解决方案。但是似乎没有什么可以使烦人的通知声音静音。它在 SDK25 上被静音。但在 SDK 29 模拟器上,它不会被静音。有什么解决办法?
代码:
//service
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
createNotificationChannel()
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, 0
)
val notification: Notification =
NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("app_name")
.setContentText("Updating database.")
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build()
startForeground(1, notification)
thread() {
Thread.sleep(3000)
stopSelf()
}
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = SettingsHelper.KEY_NOTIFICATION_channel_name_service
val description = SettingsHelper.KEY_NOTIFICATION_CH_ID_SERVICE
val channel = NotificationChannel(
SettingsHelper.KEY_NOTIFICATION_CH_ID,
name,
NotificationManager.IMPORTANCE_NONE
)
channel.description = description
channel.setSound(null, null)
val manager = getSystemService(
NotificationManager::class.java
)
manager.createNotificationChannel(channel)
}
}
【问题讨论】:
-
您能否发布所有用于创建通知的代码?
-
@Skizo-ozᴉʞS 我已更新所有服务代码以重现。它会播放通知声音。
-
你试过用空的声音文件代替null吗?
-
@Rifat 你试过我的解决方案了吗?
-
@Skizo-ozᴉʞS 当我使用 NotificationCompat.Builder 时,我不必使用
setSilent(),默认情况下它是无声的。为了安全起见,我还是使用了它。感谢您的建议和努力。
标签: android android-notifications