Push Notifications with Kotlin

Introduction

This simple app will show you how to integrate push Notifications in your kotlin android app. I will show you how to setup firebase for your project and how to display your push notification on your devices. Lets begin.

First add Firebase support to your app by clicking on Tools > Firebase >

Next Select Cloud Messaging and follow these steps >

Select “Set up Firebase Coud Messaging” then click “Connect to Firebase”, after synced up with one of your Gmail account, a Firebase project with the same name of your project will be created on your Firebase account.

After that is completed we can Click “Add FCM to your app” -> “Accept Changes”, it will update the required configurations and sync the whole project.

And thats its. We have successfully integrated Firebase to your app.

Next we will create a service class to handle our payload from the cloud by creating a class MyFirebaseMessagingService.kt and declaring it in the Manifest.

MyFirebaseMessagingService.kt

import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService : FirebaseMessagingService() {
    val TAG = String::class.java.simpleName
    
        override fun onNewToken(token: String) {
        super.onNewToken(token)
        // Send your token here
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) { 
        if (remoteMessage.notification != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.notification!!.body)
        }
    }
}

Manifest

    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    
    And add the Internet permisssion

<uses-permission android:name="android.permission.INTERNET"/>

Before we continue in displaying the notification on a device we can quickly text if our data arrives safely by send a message from the Firebase dashboard as demostrated below > Link (console.firebase.google.com)

Next click Target and select your app id

You can skip the next steps as they are optional. After completed send the message and we will see that it is delivered in our MyFirebaseMessagingService class when debuged.

Now that the Firebase is working fine we can create a notification on our device whenever a push payload arrives. So we will make a method that displays the notification on the notification bar.

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    if (remoteMessage.notification != null) {
        val title : String = remoteMessage.notification?.title!!
        val body : String = remoteMessage.notification?.body!!
        addNotification(title, body)
    }
}

private fun addNotification(title: String, body: String) {
    val builder: Notification.Builder? = Notification.Builder(this)
        .setSmallIcon(R.drawable.user_icon) //set icon for notification
        .setContentTitle(title) //set title of notification
        .setContentText(body) //this is notification message
        .setAutoCancel(true) // makes auto cancel of notification
        .setPriority(NotificationCompat.PRIORITY_DEFAULT) //set priority of notification
    val notificationIntent = Intent(this, MainActivity::class.java)
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    //notification message will get at NotificationView
    notificationIntent.putExtra("message", body)
    val pendingIntent = PendingIntent.getActivity(
        this, 0, notificationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    )
    builder?.setContentIntent(pendingIntent)
    // Add as notification
    val manager =
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    manager.notify(0, builder?.build())
}

Demo

Thats it. All your data will be handled in this class and you can send your token to your api and handle all your payload. When you click on the Notification it simply takes you to MainActivity but you can handle it however you deem ok.