Add Firebase to an existing android project
Click Tools -> Firebase
A new firebase sidebar will appear. From that click Set up Firebase Cloud Messaging
Next click on Connect to Firebase. It will ask to login to firebase console with gmail account. Then follow the instructions.
After that click on Add FCM to your app then follow the instructions.
Receiving message from FCM
Create a new kotlin class called MyFirebaseMessagingService.kt
and add this following code:
class MyFirebaseMessagingService: FirebaseMessagingService() {
val TAG = "FirebaseMessagingService"
override fun onNewToken(token: String?) {
super.onNewToken(token)
Log.d("TOKEN", token)
}
@SuppressLint("LongLogTag")
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d(TAG, remoteMessage.from)
if (remoteMessage.notification != null) {
showNotification(remoteMessage.notification?.title, remoteMessage.notification?.body)
}
}
// show notification
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())
}
}
Then from AndroidManifest.xml
add this service:
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Push notification from the console dashboard
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 the application package name. Next (optional).
After finish click Review then Publish
Trigger push notification
So by default, we will set FirebaseMessaging to automatically subscribe to topic GENERAL
FirebaseMessaging.getInstance().subscribeToTopic("GENERAL")
Then when we want to turn off the notification, we just need to unsubscribe from this topic
FirebaseMessaging.getInstance().unsubscribeFromTopic("GENERAL")
Please refer to this Github link
Thank you!