October 21, 2024
Chicago 12, Melborne City, USA
Android

How to show bottomsheet inside a composable after receiving FireBase Notification


Below this the firebase class. After receiving notification I want to show a bottomSheet inside a composable. One viewModel is linked with that composable,

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<String, String>) {
        // [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()
        }
    }
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video