To push notification to a particular device, the sender either needs the user’s device FCM token or the user should subscribe to a particular topic. One advantage of sending notifications via token, the server can send notifications to active users. To follow this practice, tokens need to be saved to the server or database. But the FCM device token follows some expiration policy. FCM token gets revoked on the following triggers:
- Uninstall from a Particular device and install on a new device with the same credentials.
- User clears app data.
We will examine obtaining the device FCM token and saving it to Firebase Realtime Database in this lesson. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1:
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Refer to this article to add Firebase to your Android App.
Step 2:
Click on tools under the menu bar section and click on Firebase and include Cloud Messaging dependencies into your build file.
Step 3:
Add the below dependency to the app build file for firebase Real-time storage and sync the script.
implementation 'com.google.firebase:firebase-common-ktx:20.2.0' implementation 'com.google.firebase:firebase-database:20.1.0' implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
Add rules to the Realtime Storage rules. Please read real-time storage rules documentation for the writing rules below implementation should not be implemented in production.
{ "rules": { ".read": true, ".write": true } }
Step 4:
Add the following line in Application Manifest File
<uses-permission android:name="android.permission.INTERNET"/>
Step 5:
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
<? xml version = "1.0" encoding = "utf-8" ?>
< androidx.constraintlayout.widget.ConstraintLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< ImageView
android:id = "@+id/imageView2"
android:layout_width = "185dp"
android:layout_height = "186dp"
android:layout_marginTop = "32dp"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toTopOf = "parent"
app:srcCompat = "@mipmap/ic_gfg_foreground" />
< TextView
android:id = "@+id/textView"
android:layout_width = "278dp"
android:layout_height = "169dp"
android:layout_marginTop = "44dp"
android:gravity = "center"
android:text = "Welcome"
android:textColor = "@color/green"
android:textSize = "50sp"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintHorizontal_bias = "0.496"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toBottomOf = "@+id/imageView2" />
< Button
android:id = "@+id/button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginTop = "88dp"
android:text = "Obtain token and save"
android:textAppearance = "@style/TextAppearance.AppCompat.Large"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintEnd_toEndOf = "parent"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintTop_toBottomOf = "@+id/textView"
app:layout_constraintVertical_bias = "0.0" />
</ androidx.constraintlayout.widget.ConstraintLayout >
|
Step 6:
Refer to the code below to see how an FCM token can be retrieved and stored in the Firebase Realtime database. To understand the code, please note the comments. If the token expires, the code can be used. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
package com.geeksforgeeks.fcmpost
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.database.ktx.database
class MainActivity : AppCompatActivity() {
private lateinit var textview : TextView
private lateinit var button : Button
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// textview reference
textview = findViewById(R.id.textView)
// button reference
button = findViewById(R.id.button)
// realtime database reference
val realtimeDatabase = Firebase.database
// button on click, firebase
// token will obtain on clicking
button.setOnClickListener {
// Retrieving the FCM token
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
textview.text = "Fetching FCM registration token failed"
return @OnCompleteListener
}
// fetching the token
val token = task.result
textview.text = "Token saved successfully!"
// directory reference
val tokenDirRef = realtimeDatabase.getReference( "Tokens" )
// storing the value
tokenDirRef.setValue(token.toString())
// toast to show message
Toast.makeText(
baseContext,
"Firebase Generated Successfully and saved to realtime database" ,
Toast.LENGTH_SHORT
).show()
})
}
}
} |
This is how the token will be saved in Realtime Firebase Database
Output: