Я использую обменение облыми Firebase Cloud, чтобы отправить уведомления пользователям об обновлениях в моем приложении Android. Уведомления работают нормально, когда приложение находится на переднем плане, но когда приложение находится в фоновом режиме или закрыто, я испытываю две проблемы: < /p>
Значок уведомления - это просто пустой круг вместо указанного Drawable (r.drawable.notification_icon).
Нажимая уведомление открывает приложение вместо предполагаемого URL (который должен открыть веб -страницу).
Я думаю, что это может быть связано с контекстом, но я Уже попыталась использовать ApplicationContext, и проблема все еще происходит. < /p>
Моя реализация: < /p>
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Get the notification data
val notification = remoteMessage.notification
val notificationIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/georgeclensy/escape"))
if (notification != null) {
notification.title?.let { title ->
notification.body?.let { body ->
sendNotification(
this, title, body, "updates", "Updates", notificationIntent
)
}
}
}
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("FCM", "New token: $token")
}
}
fun sendNotification(context: Context, title: String, message: String, channelID: String, channelName: String, intent: Intent) {
val notificationId = 1
// Create a notification channel (only needed for Android 8.0+)
val channel = NotificationChannel(
channelID,
channelName,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = channelName
}
val pendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notificationManager: NotificationManager =
context.getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
// Build the notification
val notification = NotificationCompat.Builder(context, channelID)
.setSmallIcon(R.drawable.notification_icon) // This is showing as a blank circle
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build()
with(NotificationManagerCompat.from(context)) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
return
}
notify(notificationId, notification)
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... ebase-clou
Не удается получить правильный значок или намерения при отправке уведомления через обмен облачными сообщениями Firebase ⇐ Android
Форум для тех, кто программирует под Android
1739920501
Anonymous
Я использую обменение облыми Firebase Cloud, чтобы отправить уведомления пользователям об обновлениях в моем приложении Android. Уведомления работают нормально, когда приложение находится на переднем плане, но когда приложение находится в фоновом режиме или закрыто, я испытываю две проблемы: < /p>
Значок уведомления - это просто пустой круг вместо указанного Drawable (r.drawable.notification_icon).
Нажимая уведомление открывает приложение вместо предполагаемого URL (который должен открыть веб -страницу).
Я думаю, что это может быть связано с контекстом, но я Уже попыталась использовать ApplicationContext, и проблема все еще происходит. < /p>
Моя реализация: < /p>
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Get the notification data
val notification = remoteMessage.notification
val notificationIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/georgeclensy/escape"))
if (notification != null) {
notification.title?.let { title ->
notification.body?.let { body ->
sendNotification(
this, title, body, "updates", "Updates", notificationIntent
)
}
}
}
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("FCM", "New token: $token")
}
}
fun sendNotification(context: Context, title: String, message: String, channelID: String, channelName: String, intent: Intent) {
val notificationId = 1
// Create a notification channel (only needed for Android 8.0+)
val channel = NotificationChannel(
channelID,
channelName,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = channelName
}
val pendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notificationManager: NotificationManager =
context.getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
// Build the notification
val notification = NotificationCompat.Builder(context, channelID)
.setSmallIcon(R.drawable.notification_icon) // This is showing as a blank circle
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build()
with(NotificationManagerCompat.from(context)) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
return
}
notify(notificationId, notification)
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79445283/cant-get-correct-icon-or-intent-when-sending-notification-through-firebase-clou[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия