Android Push Notifications

Kevin FOO
Feb 24, 2021

This is a tutorial on how to add push notifications to your Android app with Firebase Cloud Messaging (FCM) from scratch.

Package name is important here to configure Firebase later.
This package name needs to be the same as the one in your Android project
At the project level build.gradle , add the classpath and click “Sync Now”
classpath 'com.google.gms:google-services:4.3.5'
At the app level build.gradle , add the lines as shown and click “Sync Now”
apply plugin: 'com.google.gms.google-services'implementation platform('com.google.firebase:firebase-bom:26.5.0')implementation 'com.google.firebase:firebase-messaging-ktx'
implementation 'com.google.firebase:firebase-analytics-ktx'
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
class MyFirebaseMessagingService : FirebaseMessagingService(){
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, remoteMessage.toString())
}
}
Added a button and a multi line text
val btn = findViewById(R.id.button) as Button
val txt = findViewById (R.id.editTextTextMultiLine) as EditText
btn.setOnClickListener {
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if
(!task.isSuccessful) {
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}

// Get new FCM registration token
val token = task.result

// Log and toast
Log.d(TAG, token)
txt.setText(token)
})
}
You’ll need this FCM registration token to send push notifications to this device

Set up a Firebase Cloud Messaging client app on Android

< Back to all the stories I had written

--

--

Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.