Пожалуйста, у меня есть 2 листа и 1 Popover , которые я пытаюсь запустить обмен сообщениями Firebase с помощью ключа: notification_type , запрограммированный в Kotlin. Логотип только что появляется на листовой панели уведомлений без какого -либо значка, но он запускает лист и поповер, чтобы появиться, когда вы его открываете. MainActivity , который запускает лист или поповер, я хочу через Firebase. Но когда приложение открыто, оно не показывает.
mainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize Firebase
FirebaseApp.initializeApp(this)
if (!checkPermissions()) {
requestPermissions()
}
val notificationType: String? = intent.getStringExtra("notification_type")
Log.d("MainActivity", "Received notification_type: $notificationType")
setContent {
// Pass the notification extra to HSMApp.
HSMApp(notificationType = notificationType)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent) // Ensure the new intent is used
val notificationType: String? = intent.getStringExtra("notification_type")
Log.d("MainActivity", "New Intent notification_type: $notificationType")
setContent {
HSMApp(notificationType = notificationType)
}
}
myfirebasemessaging:
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Check if the message contains notification payload
remoteMessage.notification?.let {
showNotification(it.title, it.body, remoteMessage.data["type"])
}
// Check if the message contains data payload
if (remoteMessage.data.isNotEmpty()) {
val title = remoteMessage.data["title"]
val message = remoteMessage.data["message"]
val type = remoteMessage.data["type"] // Expected: "devotional", "quiz", "word_for_the_day"
if (!type.isNullOrEmpty()) {
handleFirebaseEvent(type)
showNotification(title, message, type) // Ensure notification is displayed for data messages
} else {
showNotification(title, message, null)
}
}
}
private fun handleFirebaseEvent(type: String) {
// Create an explicit intent using our constant, then broadcast it.
val intent = Intent(NOTIFICATION_TRIGGER_ACTION).apply {
putExtra("type", type)
}
sendBroadcast(intent)
}
private fun showNotification(title: String?, message: String?, type: String?) {
val channelId = "default_channel_id"
val channelName = "Default Channel"
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Create a notification channel with high importance for heads-up notifications
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_HIGH
).apply {
description = "Default channel for app notifications"
enableLights(true)
enableVibration(true)
}
notificationManager.createNotificationChannel(channel)
}
// Make sure the Intent correctly passes "notification_type"
val intent = Intent(this, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
putExtra("notification_type", type)
}
val pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.logo_image) // Ensure this icon is white on transparent background
.setColor(Color.parseColor("#660d77"))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
// For pre-Oreo devices, set high priority.
.setPriority(NotificationCompat.PRIORITY_HIGH)
// Use defaults for sound, vibration, etc.
.setDefaults(NotificationCompat.DEFAULT_ALL)
notificationManager.notify(0, notificationBuilder.build())
}
override fun onNewToken(token: String) {
Log.d("MyAppFCM", "New token: $token")
sendTokenToServer(token)
}
private fun sendTokenToServer(token: String) {
Log.d("FCM", "Firebase token: $token")
// TODO: Implement API call to send the token to your backend
}
}
hsmapp:
HSMAppTheme {
MainScreen(
onDismiss = {
isDevotionalSheetVisible = false
isQuizSheetVisible = false
isWordPopupVisible = false
isMailSheetVisible = false
},
showDevotionalSheet = { isDevotionalSheetVisible = true },
showQuizSheet = { isQuizSheetVisible = true },
showWordPopup = { isWordPopupVisible = true },
showMailSheet = { isMailSheetVisible = true } // Add this
)
if (isDevotionalSheetVisible) {
DevotionalSheet(onDismiss = { isDevotionalSheetVisible = false })
}
if (isQuizSheetVisible) {
QuizSheet(onDismiss = { isQuizSheetVisible = false })
}
if (isWordPopupVisible) {
WordForTheDayPopup(onDismiss = { isWordPopupVisible = false })
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... y-when-app
Firebase не показывает значка, когда закрыта, но запускает простыни и всплывающие окна, только когда приложение закрыто ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Эффективно удалить всплывающие окна с веб-сайтов, прежде чем сделать снимки экрана [закрыто]
Anonymous » » в форуме Html - 0 Ответы
- 10 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Эффективно удалить всплывающие окна с веб-сайтов, прежде чем сделать снимки экрана [закрыто]
Anonymous » » в форуме Html - 0 Ответы
- 12 Просмотры
-
Последнее сообщение Anonymous
-