【发布时间】:2020-07-10 20:04:03
【问题描述】:
我正在为我的 Android 应用程序使用 Firebase FCM 服务。面对其中列出的问题。
- 有时当应用程序收到通知时它不会发出声音。下面是代码sn-p。
private fun createNotificationChannel(
context: Context, id: String, name: String, description: String,
path: Uri?, dnd: Boolean, importance: Int,
notificationManager: NotificationManager
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val existingChannel =
notificationManager.getNotificationChannel(id)
if (existingChannel != null) {
notificationManager.deleteNotificationChannel(id)
}
val mAudioManager =
context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
mAudioManager.setStreamVolume(
AudioManager.STREAM_ALARM,
mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM),
0
)
val channel = NotificationChannel(id, name, importance)
channel.description = description
channel.enableLights(true)
channel.setShowBadge(true)
channel.describeContents()
channel.setBypassDnd(dnd)
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
channel.lightColor = R.color.red
channel.enableVibration(true)
if (id == CHANNEL_ID_NORMAL_PRIORITY) {
if (!SharedPrefUtils.getSharedPrefIsAppInForeground(context)) {
channel.setSound(
path,
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
)
}
} else if (id == CHANNEL_ID_HIGH_PRIORITY) {
channel.setSound(
path,
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
)
}
notificationManager.createNotificationChannel(channel)
}
}
- 如果 App 长时间未运行,则不会调用 firebase 消息服务的 onMessageReceived() 方法。在这种情况下,当应用程序进入前台时,我会收到通知。
- 在推送通知中,我只发送数据负载,因为当应用程序处于后台(运行或关闭)并接收通知时,如果我们使用通知负载,它不会为横幅设置大图标。下面是推送通知的代码 sn-p。
AndroidConfig androidConfig = AndroidConfig.builder()
.setTtl(3600 * 1000)
.setPriority(AndroidConfig.Priority.HIGH)
//.setNotification(androidNotification)
.putData("title", title)
.putData("body", StringEscapeUtils.unescapeJava(content))
.putData("icon", icon)
.putData("sound", soundData)
.putData("channelid", channelId)
.build();
Message msg = Message.builder()
.setAndroidConfig(androidConfig)
.setToken(token)
.build();
String response = FirebaseMessaging.getInstance().send(msg);
【问题讨论】:
-
“如果 App 长时间未运行,则不会调用 firebase 消息服务的 onMessageReceived() 方法” 这将取决于您发送的消息类型到您的应用程序(通知消息或数据消息)。对于通知消息,
onMessageReceived仅在您的应用位于前台时才会调用。否则消息将被传递到系统通知托盘。 -
嗨迈克尔,我只使用数据消息。
标签: android kotlin firebase-cloud-messaging