👨‍💻
Sagar R. Kothari
  • README
  • _posts
    • 2019-08-13-Start-apache-server
    • Preview
    • 2020-02-12-SwiftUICardView
    • 2019-04-10-12-Swift5
    • 2021-07-11-Android-Basic-Setup
    • 2021-01-25-Android-Retrofit
    • 2020-02-05-BinaryTree-PostOrder-Traversal
    • 2020-02-06-Array-Rotation
    • 2019-04-12-14-JekyllGenerateCategoriesPage
    • 2020-09-28-nodejs
    • 2020-07-03-Android-Kotlin-Clickable-RecyclerView
    • 2021-01-24-Android-Kotlin-hideKeyboard
    • 2020-07-17-Android-NavigationComponent-SafeArgs
    • 2020-01-31-SinglyLinkList-RemoveThoseTotalZero
    • 2020-02-18-SwiftJustDayValue
    • 2021-05-29-Android-BottomSheet
    • 2020-02-05-BinaryTree-Search
    • 2020-02-03-FontForNumbersAndCurrency
    • 2020-07-01-Anroid-Kotlin-ListView
    • 2020-01-30-SinglyLinkList-Display
    • 2020-01-31-SinglyLinkList-Delete-Head
    • 2020-07-03-Anroid-Kotlin-RecyclerView
    • MainActivity.kt
    • 2021-05-29-Android-DropDown
    • Example 1
    • 2020-02-20-Swift-Form-Data-Request
    • 2020-01-31-SinglyLinkList-Delete-Before
    • 2020-02-19-UndoLastCommit
    • 2020-02-24-Swift-UIImagePickerController
    • Sample Fastlane Script to upload to fabric/crashlytics
    • 2021-02-09-Android-Switch
    • 2020-02-13-SwiftUI-ListViewWithSwipeDelete
    • 2020-07-05-Anroid-Kotlin-RecyclerView-Retrofit
    • 2021-01-25-Android-Configs
    • Convert SVG to png macOS command
    • build.gradle (Module: app)
    • 2020-07-15-Android-Kotlin-NavDrawer
    • 2020-02-05-BinaryTree-InOrder-Traversal
    • 2021-01-25-Android-NavPop
    • 2019-04-10-16-XcodeShortCuts
    • 2021-02-10-Android-Button-icon
    • 2019-08-12-CloudKit-DataSync
    • 2020-02-10-DSLinkListSwapNodes
    • 2020-02-18-SwiftDarkOrLightMode
    • 2020-02-02-Swift-Array-Chunked-Stride
    • 2020-02-16-OpenShareSheet
    • 2020-07-19-Android-NavigationComponent-NavDrawer
    • 2019-04-12-13-Swift-SHA256
    • 2020-07-18-Android-Share-Intent-Text
    • 2021-07-11-Android-Read-SMS
    • 2020-07-10-Anroid-RootCheck
    • Important Folder Locations for iOS App Developer
    • 2021-01-25-Android-Navigation-Animation
    • Sample Fastlane Script to upload to MS App Center
    • 2021-01-25-Android-UDID
    • 2020-07-14-FCM-ForeBack
    • 2019-04-10-18-TimezoneFromISO8601Date
    • 2020-01-31-SinglyLinkList-Delete-After
    • MainActivity.kt
    • 2019-04-12-11-DateTimeFormatterJekyll
    • 2020-07-01-Anroid-Kotlin-ListView-ImageDownload
    • 2020-01-31-SinglyLinkList-Delete-End
    • 2020-01-31-Fastlane-build-ios-simulator
    • 2019-04-10-19-Useful-tools
    • Pre-commit script for iOS projects for automated code review
    • How do I Validate email address?
    • 2019-04-12-15-SwiftDateExtension
    • 2020-02-05-BinaryTree-PreOrder-Traversal
    • 2020-02-05-BinaryTree-HeightOfTree
    • 2019-04-12-12-FormattingDoubleAsCurrency
    • 2020-02-05-BinaryTree-LevelOrder-Traversal
    • 2020-07-13-Anroid-KillApp
    • 2020-07-20-Android-Share-Intent-Image
    • 2020-02-15-AskForAppReview
    • 2019-04-12-10-TableViewHideSearchBar
    • 2020-02-18-SwiftSizeClass
    • Preview
    • 2020-02-05-BinaryTree-Insert
    • 2021-02-07-Android-Device-Lock
    • How do I show or hide password?
    • 2020-01-30-SinglyLinkList-Middle
    • 2020-07-16-Android-NavigationComponent
    • 2021-02-12-Android-Regex
    • 2020-01-31-SinglyLinkList-Insert-Before
    • 2021-02-10-Android-Button-Background
    • 2020-01-30-SinglyLinkList-Insert-atEnd
    • 2019-05-24-codeSnipsForVue
    • 2020-07-12-Anroid-EventBus
    • 2020-07-11-Anroid-Background-Foreground-Check
    • 2020-02-19-macOSCatalyst-AvoidPods
    • 2021-02-07-Android-Is-Internet-connected
    • 2020-02-07-SwiftUI-ImagePicker
    • 2020-02-04-Swift-IAP-Receipt-Validation
    • 2021-02-08-Android-hard-space
    • 2020-01-30-SinglyLinkList-Inverse
    • 2020-01-29-Swift-iCloud-check
    • 2021-01-24-Android-Kotlin-FragmentLayoutBinding
    • 2019-08-08-Pods-I-use
    • 2019-04-12-18-AddAcknowledgement
    • 2020-02-17-macOSCatalyst-HideTitleBar
    • 2019-04-12-16-isLive
    • 2020-07-02-Anroid-Kotlin-Volley-Get-GitUsers
    • 2019-04-13-11-SwiftRelativeDate
    • 2019-04-12-19-ChangeBarButtonFont
    • 2020-02-09-Swift-Equatable
    • 2021-02-13-Android-show-hide-menu
    • 2020-02-12-SwiftUI-List-withCardView
    • 2020-02-12-SwiftUIFabAction
    • 2019-08-08-zsh-git-commands
    • 2020-07-04-Anroid-Kotlin-RecyclerView-SwipeRefresh
    • 2020-01-30-PlayVideo
    • 2020-02-08-Swift-Reduce-Example
    • Generating App Icons from Single image named 1024x1024.png
    • Mocking data with Mocky and randomuser
    • 2020-02-14-Swift-PerformTaskInBackground
    • 2020-01-31-Github-Actions-Fastlane
    • 2020-02-25-Swift-UIImage-Resize
    • Preview
    • 2020-02-11-macOS-Mouse-Hover-Highlight
    • 2021-01-26-Android-Secure-Pref
    • 2020-02-07-SwiftUI-List-RemoveSeparator
    • 2020-01-30-SinglyLinkList-Insert-atHead
    • 2020-01-31-SinglyLinkList-Insert-After
    • 2020-01-31-SinglyLinkList-RemoveLoop
    • 2020-02-10-DSRecursionReverse
    • 2020-02-01-Swift-Reachability
    • 2021-02-11-Android-Copy-to-Clipboard
    • 2019-04-12-17-UsingCocoaLumberjack
    • 2020-02-07-SwiftUI-Pop-Navigation
    • 2020-07-05-Anroid-Kotlin-RecyclerView-ScrollToEnd
    • 2020-09-26-nodejs
    • 2020-07-03-Android-Kotlin-RecyclerView-PullToRefresh
    • Sample fastlane script to upload your app to TestFlight
  • tag
    • code
    • jekyll
    • customizations
    • analytics
    • installation
    • tags
    • images
    • comments
  • Tags
  • MyBookmarks
  • admin
  • Some info
Powered by GitBook
On this page
  • build.gradle (Module: app)
  • Step 1: MyFirebaseMessagingService - Observe Foreground / Background
  • Step 2. Data Class for notification object.
  • Step 3: MyFirebaseMessagingService onMessageReceived - Send data using EventBus if App is in foreground
  • Step 4: Receive Data from Event Bus if App is in foreground.
  • Step 5: Send notification if app is in background
  • 6. Read data from Notification when app was killed but launched using Notification.

Was this helpful?

  1. _posts

2020-07-14-FCM-ForeBack

Previous2021-01-25-Android-UDIDNext2019-04-10-18-TimezoneFromISO8601Date

Last updated 4 years ago

Was this helpful?

Before we read this, please make sure you've completed reading following articles.

build.gradle (Module: app)

dependencies {
    ...
    implementation 'androidx.lifecycle:lifecycle-process:2.2.0'
    implementation 'org.greenrobot:eventbus:3.2.0'
    ...
}

Step 1: MyFirebaseMessagingService - Observe Foreground / Background

Add LifecycleObserver to your MyFirebaseMessagingService class.

class MyFirebaseMessagingService : FirebaseMessagingService(), LifecycleObserver {
    private var isAppInForeground = false
    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        ProcessLifecycleOwner.get().lifecycle.removeObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onForegroundStart() {
        isAppInForeground = true
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onForegroundStop() {
        isAppInForeground = false
    }
}

Step 2. Data Class for notification object.

data class NotificationData(
    val body: String,
    val clickAction: String,
    val title: String
)

Step 3: MyFirebaseMessagingService onMessageReceived - Send data using EventBus if App is in foreground

Check - If App is running & on forground, pass data using event-bus. Only If app is in background / killed, show notification

// MyFirebaseMessagingService.kt

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)

        // Push Notification object MUST NOT contain `notification` for Android
        // If it has `notification` object, controll will pass to Android.
        // and when app is killed our App won't get control.
        // So, server/platform must send push-notification using `data` object 
        // and must avoid `notification`


        // We MUST READ values from Data
        val messageText = message.data.get("body") ?: "No Message Body"
        var clickAction = message.data.get("click_action") ?: ""
        val title = message.data.get("title") ?: "MyApplication"
        val components = clickAction.split("?type=")
        clickAction = if (components.count() == 2) components[1] else ""
        if(isAppInForeground && clickAction.isNotBlank()) {
            EventBus.getDefault().post(NotificationData(messageText, clickAction, title))
        } else {
            sendNotification(NotificationData(messageText, clickAction, title))
        }
    }

Step 4: Receive Data from Event Bus if App is in foreground.

class MainActivity : AppCompatActivity() {
    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onThrowEvent(data : NotificationData) {
        // your preferred set of actions here.
        // Here I'm showing a snackbar.
        if (data.clickAction.isNotEmpty()) {
            val snack = Snackbar.make(
                this@MainActivity.containerView, // Use your view to show Snackbar
                data.body,
                Snackbar.LENGTH_LONG
            )
            snack.setAction("Open", View.OnClickListener {
                // Do something when user taps on open
            })
            snack.show()
        }
    }
}

Step 5: Send notification if app is in background

// MyFirebaseMessagingService.kt

    private fun sendNotification(data: NotificationData) {
        // 1. Get Intent of activity which you want to be launched
        val intent = Intent(this.applicationContext, MainActivity::class.java)
        // 2. Add Flags
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
        // 3. Add Extras
        intent.putExtra("message", data.body)
        intent.putExtra("clickAction", data.clickAction)

        // 4. Create Pending Intent (Intent yet to launch) with above intent
        val pendingIntent = TaskStackBuilder.create(this)
             .addNextIntentWithParentStack(intent)
             .getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT)

        // 5. Default sound for notification.
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        // 6. Create NotificationCompact Object
        val notificationBuilder = NotificationCompat.Builder(this, "ChannelID")
            .setSmallIcon(R.mipmap.ic_launcher_round) // 6.1 Set Small Icon - MUST
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round)) // 6.2 Set Large Icon - optional
            .setContentTitle(data.title) // 6.3 Set Content Title - MUST
            .setContentText(data.body) // 6.3 Set Content Text - MUST
            .setAutoCancel(true) // 6.4 notification is automatically canceled when the user clicks it in the panel
            .setSound(defaultSoundUri) // 6.5 Set sound
            .setContentIntent(pendingIntent) // 6.6 set pending intent - IMPORTANT

        // 7. With notification manager, send above notification using above object object
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("MyApplication",
                "MyApplication Push Notifications",
                NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }
        notificationManager.notify(0, notificationBuilder.build())
    }

6. Read data from Notification when app was killed but launched using Notification.

// MainActivity.kt

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val clickAction: String? = intent.extras?.get("clickAction") as String?
        val message: String? = intent.extras?.get("message") as String?
    }
Event Bus in Android
Background Check