Sun. Dec 22nd, 2024

To add Firebase Cloud Messaging (FCM) to your Android app and generate a device token, follow these steps:

Step 1: Set Up Firebase Project

  1. In the Firebase Console, create or select your project.
  2. Follow the instructions to add your Android app to the project (if not done already).
  3. Download the google-services.json file and place it in your app’s app directory.

Step 2: Add Firebase Dependencies

In your project’s build.gradle files:

  1. Project-level build.gradle file: Add the Google services plugin if it’s not already there:
   classpath 'com.google.gms:google-services:4.3.14' // Check for latest version
  1. App-level build.gradle file:
  • 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
  1. 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

  1. Run the app on a physical device or emulator with Google Play services.
  2. Open Logcat in Android Studio and filter by “FCM” to see the token.
  3. 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:

  1. Go to Firebase Console > Cloud Messaging.
  2. Click Send your first message.
  3. Enter a title and message, and under Target, select your app.
  4. Click Test on device, then enter your device token to target the specific device.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *