This is a tutorial on how to add push notifications to your Android app with Firebase Cloud Messaging (FCM) from scratch.
classpath 'com.google.gms:google-services:4.3.5'
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())
}
}
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)
})
}