Push Notifications using FirebaseCloudMessaging on Android

FCM image

The flow of the Article:
1. What is Firebase Cloud Messaging?
2. How to Send Push Notifications in Android?

What is Firebase Cloud Messaging?

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages. using FCM you can send notifications displayed to users and increase app re-engagement or send data messages to your app.
You can send messages in 3 ways:
1. To a single device.
2. To a group of devices.
3. To a group using subscribed topics.

You can send two types of messages:
1. Notification Messages.
2. Data Messages

How to Send Push Notifications in Android?

First, I will show you how to send push notifications without even writing one single code related to notifications just using Firebase notification composer.

Step1: Create an Android project

Step 2: You need to connect your Android project with Firebase to do that at the top you find tools go to Firebase

click on it you get firebase assistant and choose cloud messaging and
first, it shows to connect to Firebase do that

click on Connect to Firebase and it will open up the Firebase console and create a Firebase project

after creating a firebase it will automatically put the google-services.json file in the Android project.

Now, click on Add FCM to your app you can use BOM way as well.

After it is done go to Firebase Console and find Messaging.

Step 3: Now, click on a new campaign and choose notification.

and fill in the details and click next
in Target you will target all apps

You can fill just click review
click on Publish

Note: Before sending a push notification make sure you run the App and it is in the background as we have not handled notification in app so fcm sdk will handle notification in background only. later we will handle notification in foreground as well

You will receive a notification like below

FCM SDK will automatically create a Miscellaneous notification channel if you have not mentioned any channel name.

Now, let’s handle notifications in the foreground.
You need to extend FirebaseMessagingService

class MyFirebaseMessagingService: FirebaseMessagingService() {

override fun onNewToken(token: String) {
super.onNewToken(token)
Log.i("FCM_TOKEN", token)
}

override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
message.notification?.let {
val title = it.title
val body = it.body

val notification = NotificationCompat.Builder(this, App.FCM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_comment_24)
.setContentTitle(title)
.setContentText(body)
.build()

val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1002, notification)
}

Log.i("DATA_MESSAGE", message.data.toString())
}
}

in onMessageReceived() you get both a notification message and a data message.

So based on the message type you get data. In the Notification message, we have predefined keys which can be used to configure notifications and in the data message, you can add custom key-value pair.

Now, you have to register this service in Manifest.xml

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

Now, run the app in the foreground and now compose a notification from Firebase
You should see the message in the foreground

Note: Make sure to create a notification channel for sdk version ≥ O

class App : Application() {
companion object {
const val FCM_CHANNEL_ID = "FCM_CHANNEL_ID"
}

override fun onCreate() {
super.onCreate()
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
val fcmChannel = NotificationChannel(FCM_CHANNEL_ID, "FCM_Channel", NotificationManager.IMPORTANCE_HIGH)

val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

manager.createNotificationChannel(fcmChannel)
}
}
}

Don’t forget to ask for POST_NOTIFICATION permission for Android 13 and above

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
// Declare the launcher at the top of your Activity/Fragment:
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission(),
) { isGranted: Boolean ->
if (isGranted) {
// FCM SDK (and your app) can post notifications.
} else {
// TODO: Inform user that that your app will not show notifications.
}
}

private fun askNotificationPermission() {
// This is only necessary for API level >= 33 (TIRAMISU)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
) {
// FCM SDK (and your app) can post notifications.
} else {
// Directly ask for the permission
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}

Once permission is granted then you can see the notification when you publish.

If you want to target a single device you need to have a registration token provided by FCM token

So let’s get the token

FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.i("FCM_TOKEN", "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}

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

// Log and toast

Log.d("FCM_TOKEN1", token)
Toast.makeText(baseContext, token, Toast.LENGTH_SHORT).show()
})

So this is how you can get the token .let’s say the user clears the cache of the app or uninstalls and reinstall the app in that case you need to override the onNewToken() method in FirebaseMessagingService

class MyFirebaseMessagingService: FirebaseMessagingService() {

override fun onNewToken(token: String) {
super.onNewToken(token)
Log.i("FCM_TOKEN", token)
}
}

Now if you want to send a notification to a specific user then copy the token and paste it into Firebase notification composer and click send test message and then paste the token and click send.

You will get a notification on that device.

Now, I will show how you can send notifications by using Postman to create a POST request to send messages as sometimes your backend server sends push notifications based on some conditions so in that case you need to hit these requests.

First, open this link https://developers.google.com/oauthplayground/
select Firebase Cloud Messaging API v1 from API list and choose this
https://www.googleapis.com/auth/cloud-platform

and now click Authorize API. it will ask you to log in
after that click on the Exchange authorization code for tokens

Now you will get an Access token copy that and now copy the Firebase ProjectId as well and use this POST request https://fcm.googleapis.com/v1/projects/{YOUR_PROJECTID}/messages: send

replace with your Firebase project id and In the headers put content-type: application/JSON and authorization as Bearer {Access token}

and in the body choose raw
and paste this

{
"message": {
"token": "REPLACE_WITH_DEVICE_TOKEN",
"data": {
"key1": "hello from postman"
},
"notification": {
"title": "Postman",
"body": "notify"
}
}
}

and hit the Send button you should get a notification on the provided device token.

in this same way from your app server, you will make the request to send push notifications to devices.

That is it for the article

Thank You

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job


Push Notifications using FirebaseCloudMessaging on Android was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Shaik Ahron

FCM image

The flow of the Article:
1. What is Firebase Cloud Messaging?
2. How to Send Push Notifications in Android?

What is Firebase Cloud Messaging?

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages. using FCM you can send notifications displayed to users and increase app re-engagement or send data messages to your app.
You can send messages in 3 ways:
1. To a single device.
2. To a group of devices.
3. To a group using subscribed topics.

You can send two types of messages:
1. Notification Messages.
2. Data Messages

How to Send Push Notifications in Android?

First, I will show you how to send push notifications without even writing one single code related to notifications just using Firebase notification composer.

Step1: Create an Android project

Step 2: You need to connect your Android project with Firebase to do that at the top you find tools go to Firebase

click on it you get firebase assistant and choose cloud messaging and
first, it shows to connect to Firebase do that

click on Connect to Firebase and it will open up the Firebase console and create a Firebase project

after creating a firebase it will automatically put the google-services.json file in the Android project.

Now, click on Add FCM to your app you can use BOM way as well.

After it is done go to Firebase Console and find Messaging.

Step 3: Now, click on a new campaign and choose notification.

and fill in the details and click next
in Target you will target all apps

You can fill just click review
click on Publish

Note: Before sending a push notification make sure you run the App and it is in the background as we have not handled notification in app so fcm sdk will handle notification in background only. later we will handle notification in foreground as well

You will receive a notification like below

FCM SDK will automatically create a Miscellaneous notification channel if you have not mentioned any channel name.

Now, let’s handle notifications in the foreground.
You need to extend FirebaseMessagingService

class MyFirebaseMessagingService: FirebaseMessagingService() {

override fun onNewToken(token: String) {
super.onNewToken(token)
Log.i("FCM_TOKEN", token)
}

override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
message.notification?.let {
val title = it.title
val body = it.body

val notification = NotificationCompat.Builder(this, App.FCM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_comment_24)
.setContentTitle(title)
.setContentText(body)
.build()

val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1002, notification)
}

Log.i("DATA_MESSAGE", message.data.toString())
}
}

in onMessageReceived() you get both a notification message and a data message.

So based on the message type you get data. In the Notification message, we have predefined keys which can be used to configure notifications and in the data message, you can add custom key-value pair.

Now, you have to register this service in Manifest.xml

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

Now, run the app in the foreground and now compose a notification from Firebase
You should see the message in the foreground

Note: Make sure to create a notification channel for sdk version ≥ O
class App : Application() {
companion object {
const val FCM_CHANNEL_ID = "FCM_CHANNEL_ID"
}

override fun onCreate() {
super.onCreate()
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
val fcmChannel = NotificationChannel(FCM_CHANNEL_ID, "FCM_Channel", NotificationManager.IMPORTANCE_HIGH)

val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

manager.createNotificationChannel(fcmChannel)
}
}
}

Don’t forget to ask for POST_NOTIFICATION permission for Android 13 and above

<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
// Declare the launcher at the top of your Activity/Fragment:
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission(),
) { isGranted: Boolean ->
if (isGranted) {
// FCM SDK (and your app) can post notifications.
} else {
// TODO: Inform user that that your app will not show notifications.
}
}

private fun askNotificationPermission() {
// This is only necessary for API level >= 33 (TIRAMISU)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
) {
// FCM SDK (and your app) can post notifications.
} else {
// Directly ask for the permission
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}

Once permission is granted then you can see the notification when you publish.

If you want to target a single device you need to have a registration token provided by FCM token

So let's get the token

FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.i("FCM_TOKEN", "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}

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

// Log and toast

Log.d("FCM_TOKEN1", token)
Toast.makeText(baseContext, token, Toast.LENGTH_SHORT).show()
})

So this is how you can get the token .let's say the user clears the cache of the app or uninstalls and reinstall the app in that case you need to override the onNewToken() method in FirebaseMessagingService

class MyFirebaseMessagingService: FirebaseMessagingService() {

override fun onNewToken(token: String) {
super.onNewToken(token)
Log.i("FCM_TOKEN", token)
}
}

Now if you want to send a notification to a specific user then copy the token and paste it into Firebase notification composer and click send test message and then paste the token and click send.

You will get a notification on that device.

Now, I will show how you can send notifications by using Postman to create a POST request to send messages as sometimes your backend server sends push notifications based on some conditions so in that case you need to hit these requests.

First, open this link https://developers.google.com/oauthplayground/
select Firebase Cloud Messaging API v1 from API list and choose this
https://www.googleapis.com/auth/cloud-platform

and now click Authorize API. it will ask you to log in
after that click on the Exchange authorization code for tokens

Now you will get an Access token copy that and now copy the Firebase ProjectId as well and use this POST request https://fcm.googleapis.com/v1/projects/{YOUR_PROJECTID}/messages: send

replace with your Firebase project id and In the headers put content-type: application/JSON and authorization as Bearer {Access token}

and in the body choose raw
and paste this

{
"message": {
"token": "REPLACE_WITH_DEVICE_TOKEN",
"data": {
"key1": "hello from postman"
},
"notification": {
"title": "Postman",
"body": "notify"
}
}
}

and hit the Send button you should get a notification on the provided device token.

in this same way from your app server, you will make the request to send push notifications to devices.

That is it for the article

Thank You

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job


Push Notifications using FirebaseCloudMessaging on Android was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Shaik Ahron


Print Share Comment Cite Upload Translate Updates
APA

Shaik Ahron | Sciencx (2023-05-19T16:17:12+00:00) Push Notifications using FirebaseCloudMessaging on Android. Retrieved from https://www.scien.cx/2023/05/19/push-notifications-using-firebasecloudmessaging-on-android/

MLA
" » Push Notifications using FirebaseCloudMessaging on Android." Shaik Ahron | Sciencx - Friday May 19, 2023, https://www.scien.cx/2023/05/19/push-notifications-using-firebasecloudmessaging-on-android/
HARVARD
Shaik Ahron | Sciencx Friday May 19, 2023 » Push Notifications using FirebaseCloudMessaging on Android., viewed ,<https://www.scien.cx/2023/05/19/push-notifications-using-firebasecloudmessaging-on-android/>
VANCOUVER
Shaik Ahron | Sciencx - » Push Notifications using FirebaseCloudMessaging on Android. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/05/19/push-notifications-using-firebasecloudmessaging-on-android/
CHICAGO
" » Push Notifications using FirebaseCloudMessaging on Android." Shaik Ahron | Sciencx - Accessed . https://www.scien.cx/2023/05/19/push-notifications-using-firebasecloudmessaging-on-android/
IEEE
" » Push Notifications using FirebaseCloudMessaging on Android." Shaik Ahron | Sciencx [Online]. Available: https://www.scien.cx/2023/05/19/push-notifications-using-firebasecloudmessaging-on-android/. [Accessed: ]
rf:citation
» Push Notifications using FirebaseCloudMessaging on Android | Shaik Ahron | Sciencx | https://www.scien.cx/2023/05/19/push-notifications-using-firebasecloudmessaging-on-android/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.