Код, которым я поделился, в порядке, я могу получить данные уведомлений в logcat, но я хочу отображать данные уведомлений на одном из моих компонуемых экранов. Я не понял, как передать данные уведомления из класса firebaseNotificationService на мой составной экран.
class FireBaseNotificationServices(
private val NotificationRepository: NotificationRepository = Graph.notificationRepository
) : FirebaseMessagingService() {
private val firebaseViewModel: FirebaseViewModel by lazy {
FirebaseViewModel()
}
private val orderViewModel: OrderViewModel by lazy { OrderViewModel() }
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
Log.d(TAG, "Message ID: ${remoteMessage.messageId}")
orderViewModel.setNotificationData(NotificationDataModel(id = 0, notification_type = "new order", notification_data = remoteMessage.data.toString()))
// Check if data needs to be processed by long running job
if (needsToBeScheduled()) {
// For long-running tasks (10 seconds or more) use WorkManager.
//scheduleJob(remoteMessage.data)
} else {
// Handle message within 10 seconds
handleNow()
}
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.title}")
Log.d(TAG, "Message Notification Body: ${it.body}")
sendNotification(remoteMessage.notification?.body.toString())
firebaseViewModel.setNotificationData(it.title.toString(), it.body.toString())
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private fun needsToBeScheduled() = true
override fun onNewToken(token: String) {
sendRegistrationToServer(token)
}
private fun scheduleJob(remoteData: MutableMap) {
// [START dispatch_job]
val data = Data.Builder()
data.putString("orderId", remoteData["id"])
val work = OneTimeWorkRequest.Builder(MyWorker::class.java).setInputData(data.build())
.build()
WorkManager.getInstance(this)
.beginWith(work)
.enqueue()
// [END dispatch_job]
}
private fun handleNow() {
Log.d(TAG, "Short lived task is done.")
}
private fun sendRegistrationToServer(token: String?) {
Log.d(TAG, "sendRegistrationTokenToServer($token)")
setFirebaseToken(token.toString())
}
private fun sendNotification(messageBody: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val requestCode = 0
val pendingIntent = PendingIntent.getActivity(
this,
requestCode,
intent,
PendingIntent.FLAG_IMMUTABLE,
)
val channelId = "cws.pos.app"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT,
)
notificationManager.createNotificationChannel(channel)
}
val notificationId = 0
notificationManager.notify(notificationId, notificationBuilder.build())
}
companion object {
private const val TAG = "MyFirebaseMsgService"
}
private var scope = MainScope()
private fun setFirebaseToken(id: String) {
val dataPref = DataPref(context = applicationContext)
scope.launch {
dataPref.setFirebaseToken(data = id)
}
}
internal class MyWorker(
appContext: Context, workerParams: WorkerParameters,
) :
Worker(appContext, workerParams) {
private val orderViewModel: OrderViewModel by lazy { OrderViewModel() }
override fun doWork(): Result {
val orderId = inputData.getString("orderId")
Log.d(TAG, "doWork: $orderId")
orderId?.let {
orderViewModel.setNotificationData(NotificationDataModel(id = 0, notification_type = "new order", notification_data = orderId))
}
return Result.success()
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... otificatio
Как показать нижний лист внутри составного объекта после получения уведомления FireBase ⇐ Android
Форум для тех, кто программирует под Android
1729258718
Anonymous
Код, которым я поделился, в порядке, я могу получить данные уведомлений в logcat, но я хочу отображать данные уведомлений на одном из моих компонуемых экранов. Я не понял, как передать данные уведомления из класса firebaseNotificationService на мой составной экран.
class FireBaseNotificationServices(
private val NotificationRepository: NotificationRepository = Graph.notificationRepository
) : FirebaseMessagingService() {
private val firebaseViewModel: FirebaseViewModel by lazy {
FirebaseViewModel()
}
private val orderViewModel: OrderViewModel by lazy { OrderViewModel() }
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
Log.d(TAG, "Message ID: ${remoteMessage.messageId}")
orderViewModel.setNotificationData(NotificationDataModel(id = 0, notification_type = "new order", notification_data = remoteMessage.data.toString()))
// Check if data needs to be processed by long running job
if (needsToBeScheduled()) {
// For long-running tasks (10 seconds or more) use WorkManager.
//scheduleJob(remoteMessage.data)
} else {
// Handle message within 10 seconds
handleNow()
}
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.title}")
Log.d(TAG, "Message Notification Body: ${it.body}")
sendNotification(remoteMessage.notification?.body.toString())
firebaseViewModel.setNotificationData(it.title.toString(), it.body.toString())
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private fun needsToBeScheduled() = true
override fun onNewToken(token: String) {
sendRegistrationToServer(token)
}
private fun scheduleJob(remoteData: MutableMap) {
// [START dispatch_job]
val data = Data.Builder()
data.putString("orderId", remoteData["id"])
val work = OneTimeWorkRequest.Builder(MyWorker::class.java).setInputData(data.build())
.build()
WorkManager.getInstance(this)
.beginWith(work)
.enqueue()
// [END dispatch_job]
}
private fun handleNow() {
Log.d(TAG, "Short lived task is done.")
}
private fun sendRegistrationToServer(token: String?) {
Log.d(TAG, "sendRegistrationTokenToServer($token)")
setFirebaseToken(token.toString())
}
private fun sendNotification(messageBody: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val requestCode = 0
val pendingIntent = PendingIntent.getActivity(
this,
requestCode,
intent,
PendingIntent.FLAG_IMMUTABLE,
)
val channelId = "cws.pos.app"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT,
)
notificationManager.createNotificationChannel(channel)
}
val notificationId = 0
notificationManager.notify(notificationId, notificationBuilder.build())
}
companion object {
private const val TAG = "MyFirebaseMsgService"
}
private var scope = MainScope()
private fun setFirebaseToken(id: String) {
val dataPref = DataPref(context = applicationContext)
scope.launch {
dataPref.setFirebaseToken(data = id)
}
}
internal class MyWorker(
appContext: Context, workerParams: WorkerParameters,
) :
Worker(appContext, workerParams) {
private val orderViewModel: OrderViewModel by lazy { OrderViewModel() }
override fun doWork(): Result {
val orderId = inputData.getString("orderId")
Log.d(TAG, "doWork: $orderId")
orderId?.let {
orderViewModel.setNotificationData(NotificationDataModel(id = 0, notification_type = "new order", notification_data = orderId))
}
return Result.success()
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79102156/how-to-show-bottomsheet-inside-a-composable-after-receiving-firebase-notificatio[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия