即使在 Android 中更改后,通知声音也不会从默认值更改
Posted
技术标签:
【中文标题】即使在 Android 中更改后,通知声音也不会从默认值更改【英文标题】:Notification sound isn't changing from default, even after changing in Android 【发布时间】:2021-11-22 04:31:34 【问题描述】:我一直在尝试更改通知的声音,但它根本没有改变。 它在所有情况下都使用默认通知,即使我已经分配了频道。 请检查下面的代码,让我知道我哪里出错了。
在应用程序类中创建通知通道
class App : Application()
override fun onCreate()
super.onCreate()
createNotificationChannel()
private fun createNotificationChannel()
val ordersChannelId = "Orders"
val orderSoundUri =
Uri.parse("android.resource://" + applicationContext + "/raw/ordernotification")
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()
val VIBRATE_PATTERN = longArrayOf(0,400,800,600,800,800,800,1000)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
val ordersChannel =
NotificationChannel(ordersChannelId, "Orders", NotificationManager.IMPORTANCE_HIGH)
ordersChannel.apply
description = "This is Orders Channel"
setSound(orderSoundUri, attributes)
vibrationPattern = VIBRATE_PATTERN
importance = NotificationManager.IMPORTANCE_HIGH
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(ordersChannel)
使用 FireBaseMessagingService 创建通知
class MyFirebaseMessagingService : FirebaseMessagingService()
override fun onMessageReceived(remoteMessage: RemoteMessage)
Log.d("NotificationFire", "From: $remoteMessage?.data")
val contentIntent = Intent(applicationContext, OrderInDetailActivity::class.java)
val orderSoundUri = Uri.parse("android.resource://"+applicationContext+"/raw/ordernotification")
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()
val VIBRATE_PATTERN = longArrayOf(0, 500)
val contentPendingIntent = PendingIntent.getActivity(
applicationContext,
0,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
remoteMessage?.data?.let
Log.d("NotificationFire", "Message Notification Data: $it")
//Message Services handle notification
val notification = NotificationCompat.Builder(this, "Orders")
.setSmallIcon(R.drawable.biskit_logo)
.setContentTitle(remoteMessage.data.toString())
.setContentText(remoteMessage.data.toString())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(orderSoundUri)
.setVibrate(VIBRATE_PATTERN)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(contentPendingIntent)
.build()
val notificationManager = NotificationManagerCompat.from(this)
Log.d("NotificationFire","Notification")
notificationManager.notify(1,notification)
此代码只能以默认声音显示通知。
【问题讨论】:
我记不太清了,但是有 Android 系统设置可以覆盖这个吗?即如果用户将其设置为不允许自定义通知噪音?"android.resource://" + applicationContext + "/raw/ordernotification"
你的 uri 不应该以 .mp4
或任何你有的格式结尾吗?
【参考方案1】:
在您的声音路径中添加了 applicationContext。它将在您的路径中添加一些随机值。相反,您需要像下面这样添加包名称。
Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play
【讨论】:
以上是关于即使在 Android 中更改后,通知声音也不会从默认值更改的主要内容,如果未能解决你的问题,请参考以下文章
即使在 Flutter 中授予权限后,通知访问屏幕也会不断弹出