Create Android Push Notification Easily with Kotlin and Firebase Cloud Messaging Part 1

Bagus Aji Santoso
5 min readOct 13, 2018

--

After a long time, now I write some tutorials again for Android. I hope this tutorial could help you to create push notification in Android using Firebase Cloud Messaging

Create a new project, choose Empty Activity for a starter template. Don’t forget to give a check on Include Kotlin support.

After gradle building process finished, click on Tools > Firebase.

Connect Android Studio Project with Firebase

A new Firebase tab will appear. Click Set up Firebase Cloud Messaging as seen in the image below. If you couldn’t see it, click on Cloud Messaging part first.

Next, click Connect to Firebase. We will be redirected to login page using Gmail account.

Choose one of your account to login to Firebase website.

After that, click on Allow to continue.

If the login process succeeds, there will be a new dialog box appear on Android Studio. On the dialog box, choose Create new Firebase project and Connect to Firebase.

Wait for a moment.

Adding Firebase Dependency to Gradle

When our Android Studio project has been connected with Firebase project, we can continue with adding a new dependency so we can use Firebase Cloud Messaging. Click Add FCM to your app button.

Click on Accept Changes to add and apply the gradle dependency.

In my case, there’s a problem in build.gradle writing process by Android Studio. It put the wrong version number for firebase-messaging.

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-messaging:17.0.0:15.0.0'
}

Remove the :15.0.0 part in the last line.

implementation 'com.google.firebase:firebase-messaging:17.0.0'

Click Sync Now to continue.

Access Device Registration System

When user open our app for the first time, FCM SDK will request a new token from the Firebase server. This token then can be used to send push message to one or a group of users.

This token can be obtained using getToken() inside onTokenRefresh() method. Now, let’s implement these methods by creating a new Kotlin file, give it MyFirebaseInstanceIdService as a name.

package id.droidindonesia.pushnotificationsederhana

import android.util.Log
import com.google.firebase.iid.FirebaseInstanceId
import com.google.firebase.iid.FirebaseInstanceIdService

class MyFirebaseInstanceIdService : FirebaseInstanceIdService() {

val TAG = "PushNotifService"
lateinit var name: String

override fun onTokenRefresh() {
// Mengambil token perangkat
val token = FirebaseInstanceId.getInstance().token
Log.d(TAG, "Token perangkat ini: ${token}")

// Jika ingin mengirim push notifcation ke satu atau sekelompok perangkat,
// simpan token ke server di sini.
}

}

Next, add this Service to AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="id.droidindonesia.pushnotificationsederhana">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<!-- Add here -->
<service
android:name=".MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application>

</manifest>

Receiving Message from Firebase Cloud Messaging

Create a new Kotlin class that extends FirebaseMessagingService. Give it MyFirebaseMessagingService as its name.

package id.droidindonesia.pushnotificationsederhana

import android.annotation.SuppressLint
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import android.app.NotificationManager
import android.media.RingtoneManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat


class MyFirebaseMessagingService : FirebaseMessagingService() {
val TAG = "FirebaseMessagingService"

@SuppressLint("LongLogTag")
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "Dikirim dari: ${remoteMessage.from}")

if (remoteMessage.notification != null) {
showNotification(remoteMessage.notification?.title, remoteMessage.notification?.body)
}
}

private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT)

val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
}

Add this Service to AndroidManifest as before.

    <!-- Other code hidden to make it shorter -->

<service
android:name=".MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>

Let’s Send a Message

Now let’s us test the app. Run it to the emulator or your device. Remember that your emulator must have Google Service installed so it can receive the message.

Open https://console.firebase.google.com/, login with the account you use earlier and choose the name of our project.

In the first page, scroll down a little bit and choose Cloud Messaging.

Inside the new page, click Send your first message.

Inside Message Text, write the information you want the user to know (the long message). In Target choose User segment and in Select app choose our application package name. Below it, in Advanced options, write your title of the message inside Title. Refer to images below.

Click Send Message and Send.

I hope this tutorial helps. See you in the next article.

Code

Github repository

Zip file

--

--