To add Firebase Cloud Messaging (FCM) to your Android app and generate a device token, follow these steps:
Step 1: Set Up Firebase Project
- In the Firebase Console, create or select your project.
- Follow the instructions to add your Android app to the project (if not done already).
- Download the
google-services.jsonfile and place it in your app’sappdirectory.
Step 2: Add Firebase Dependencies
In your project’s build.gradle files:
- Project-level
build.gradlefile: Add the Google services plugin if it’s not already there:
classpath 'com.google.gms:google-services:4.3.14' // Check for latest version
- App-level
build.gradlefile:
- Apply the Google services plugin at the top:
groovy apply plugin: 'com.google.gms.google-services' - Add the Firebase Messaging dependency:
groovy implementation 'com.google.firebase:firebase-messaging:23.1.2' // Check for latest version
- Sync the project with Gradle files to download the necessary dependencies.
Step 3: Set Up Firebase Messaging Service
Create a new class that extends FirebaseMessagingService to handle token generation and messages.
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.firebase.messaging.FirebaseMessaging
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("FCM", "New token: $token")
// You can send the token to your server here if needed
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d("FCM", "Message received: ${remoteMessage.data}")
// Handle the message here if needed
}
}
Make sure to register this service in your AndroidManifest.xml file:
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Step 4: Generate and Retrieve the FCM Token
To retrieve the FCM token in your app, you can use the following code. You can call this method, for example, from MainActivity.
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.messaging.FirebaseMessaging
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Generate and retrieve FCM token
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w("FCM", "Fetching FCM registration token failed", task.exception)
return@addOnCompleteListener
}
// Get new FCM token
val token = task.result
Log.d("FCM", "FCM token: $token")
// Send token to your server or use it as needed
}
}
}
Step 5: Testing the Token Generation
- Run the app on a physical device or emulator with Google Play services.
- Open Logcat in Android Studio and filter by “FCM” to see the token.
- You should see a log message with the FCM token generated, which can be used to send push notifications to this device.
Step 6: Sending a Test Notification (Optional)
You can send a test notification from the Firebase Console:
- Go to Firebase Console > Cloud Messaging.
- Click Send your first message.
- Enter a title and message, and under Target, select your app.
- Click Test on device, then enter your device token to target the specific device.