Skip to content

A clean and modern Android sample application demonstrating Firebase Cloud Messaging (FCM) integration using Jetpack Compose and Kotlin. Features topic subscription and FCM token retrieval with a simple, intuitive UI.

Notifications You must be signed in to change notification settings

Thogaruchesti-hemanth/FCM-Compose-Sample

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”” FCM Compose Sample App

A clean, minimal Android application demonstrating Firebase Cloud Messaging (FCM) integration with Jetpack Compose and Kotlin.

Kotlin Compose Firebase minSdk

🎯 What This App Does

This sample demonstrates the core functionality of Firebase Cloud Messaging:

  • πŸ“± Topic Subscription: Subscribe your device to FCM topics with a single button tap
  • πŸ”‘ Token Management: Retrieve and log your device's unique FCM registration token
  • πŸ’¬ Push Notifications: Receive and handle cloud messages in real-time
  • 🎨 Modern UI: Clean interface built with Jetpack Compose

✨ Key Features

Feature Description
Subscribe to Topic One-tap subscription to the "general" topic for group messaging
Print FCM Token Instantly retrieve and log your device token for testing
Background Notifications Automatic notification handling when app is in background
Foreground Messages Custom message handling when app is active

πŸ“‹ Prerequisites

Before getting started, make sure you have:

  • βœ… Android Studio Hedgehog (2023.1.1) or newer
  • βœ… JDK 11 or higher
  • βœ… Android device or emulator (API 21+)
  • βœ… Google account for Firebase Console
  • βœ… Basic understanding of Kotlin and Jetpack Compose

πŸ”₯ Firebase Setup Guide

Step 1: Create Firebase Project

  1. Navigate to Firebase Console
  2. Click "Add project" or select existing one
  3. Follow the setup wizard (Google Analytics is optional)

Step 2: Register Your Android App

  1. Click the Android icon in your Firebase project
  2. Provide the following:
    • Package name: Must match your app's package (e.g., com.example.fcmsample)
    • App nickname: Optional friendly name
  3. Click "Register app"

Step 3: Download google-services.json

  1. Download the google-services.json configuration file

  2. Place it in your project's app/ directory (NOT in src/)

    YourProject/
    β”œβ”€β”€ app/
    β”‚   β”œβ”€β”€ google-services.json  ← HERE
    β”‚   β”œβ”€β”€ build.gradle.kts
    β”‚   └── src/
    
  3. Important: Add to .gitignore to keep credentials secure:

    # Firebase
    google-services.json
    

Step 4: Enable Cloud Messaging

Cloud Messaging is enabled by default for new Firebase projects. You can verify:

  • Navigate to Build β†’ Cloud Messaging in Firebase Console
  • Note your Server Key (found in Project Settings β†’ Cloud Messaging)

πŸ› οΈ Project Configuration

1. Project-level build.gradle.kts

Add the Google Services plugin to your project-level build file:

plugins {
    alias(libs.plugins.android.application) apply false
    alias(libs.plugins.kotlin.compose) apply false
    id("com.google.gms.google-services") version "4.4.4" apply false // ADD this

}

2. App-level build.gradle.kts

Apply the plugin and add Firebase dependencies:

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
    id("com.google.gms.google-services") // Add this
}

dependencies {
    // Firebase BOM
    implementation(platform("com.google.firebase:firebase-bom:32.7.0"))
    implementation("com.google.firebase:firebase-messaging-ktx")
    
    // Compose & Coroutines (versions in your project)
    // ... other dependencies
}

3. AndroidManifest.xml

Add required permissions and FCM service declaration:

<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

<!-- Inside <application> tag -->
<service
    android:name=".FCMService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

4. Sync & Build

  1. Sync Gradle files
  2. Clean and rebuild project
  3. Verify no build errors

⚠️ Common Issue: If sync fails, ensure google-services.json is in the correct location

πŸ“¦ Core Dependencies

Library Purpose
firebase-messaging-ktx FCM SDK for receiving push notifications
compose-bom Jetpack Compose Bill of Materials
material3 Material Design 3 components for UI
kotlinx-coroutines-play-services Coroutines support for Firebase APIs

πŸ—οΈ Architecture Overview

The app consists of three main components:

1. FCMService (extends FirebaseMessagingService)

  • Handles incoming push notifications
  • Manages token refresh events
  • Logs message payloads for debugging

2. MainActivity (Compose UI)

  • Displays two primary action buttons
  • Manages notification permissions (Android 13+)
  • Handles user interactions with coroutines

3. Compose Screen

  • Subscribe Button: Calls FirebaseMessaging.getInstance().subscribeToTopic("general")
  • Print Token Button: Retrieves token via FirebaseMessaging.getInstance().token
  • Shows status messages for user feedback

πŸš€ How to Use

Running the Application

  1. βœ… Ensure google-services.json is in app/ directory
  2. βœ… Sync Gradle files
  3. βœ… Build and run on a physical device (recommended) or emulator
  4. βœ… Grant notification permission when prompted (Android 13+)

App Features

πŸ”” Subscribe to Topic Button

  • Subscribes your device to the "general" FCM topic
  • Allows sending group notifications to all subscribed devices
  • Success confirmation shown on screen
  • Check Logcat filter FCM_SUBSCRIBE for detailed logs

πŸ”‘ Print Token Button

  • Retrieves your device's unique FCM registration token
  • Token is logged to Logcat (filter: FCM_TOKEN)
  • Use this token for sending targeted notifications to specific devices
  • Token format: eXXXXXX:APA91bXXXXXXX...

πŸ§ͺ Testing Push Notifications

Option 1: Firebase Console (Easiest)

  1. Open Firebase Console β†’ Engage β†’ Cloud Messaging
  2. Click "Send your first message" or "New campaign"
  3. Fill in notification details:
    • Title: "Test Notification"
    • Text: "Hello from Firebase!"
  4. Choose target:
    • Topic: general (if you subscribed)
    • Single device: Paste the FCM token from logs
  5. Click Review β†’ Publish

Option 2: Using cURL (For Developers)

Send to specific device:

curl -X POST https://fcm.googleapis.com/fcm/send \
  -H "Authorization: key=YOUR_SERVER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "DEVICE_TOKEN_HERE",
    "notification": {
      "title": "Test Title",
      "body": "Test message from cURL"
    }
  }'

Send to topic subscribers:

curl -X POST https://fcm.googleapis.com/fcm/send \
  -H "Authorization: key=YOUR_SERVER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "/topics/general",
    "notification": {
      "title": "Topic Notification",
      "body": "Message to all subscribers"
    }
  }'

πŸ’‘ Find your Server Key: Firebase Console β†’ Project Settings β†’ Cloud Messaging β†’ Server key

πŸ”§ Troubleshooting

Token Not Generating

Issue: FCM token is null or not appearing in logs

Solutions:

  • βœ… Verify google-services.json is in app/ directory (not src/)
  • βœ… Confirm package name matches Firebase Console registration
  • βœ… Check internet connectivity
  • βœ… Clean and rebuild: ./gradlew clean build
  • βœ… Invalidate caches: File β†’ Invalidate Caches β†’ Restart

Not Receiving Notifications

Issue: Notifications aren't showing up

Solutions:

  • βœ… Grant notification permission (Settings β†’ Apps β†’ Your App β†’ Notifications)
  • βœ… Disable battery optimization for the app
  • βœ… Test on a physical device (emulators can be unreliable)
  • βœ… Verify correct Server Key and device token/topic
  • βœ… Check Logcat for error messages

Build/Sync Errors

Issue: Gradle sync or build failures

Solutions:

  • βœ… Ensure Google Services plugin is applied: id("com.google.gms.google-services")
  • βœ… Validate google-services.json format (must be valid JSON)
  • βœ… Check internet connection for dependency downloads
  • βœ… Update to latest Firebase BOM version
  • βœ… Clear Gradle cache: ./gradlew clean

App Crashes on Launch

Issue: App crashes immediately after opening

Solutions:

  • βœ… Check for missing FCMService declaration in AndroidManifest
  • βœ… Verify all required permissions are declared
  • βœ… Review Logcat stack trace for specific errors
  • βœ… Ensure FCM service extends FirebaseMessagingService

πŸ’‘ Debug Tip: Always check Logcat with package name filter for detailed error messages

πŸ” Security Best Practices

  • 🚫 Never commit google-services.json to public repositories
  • πŸ“ Add to .gitignore: google-services.json
  • πŸ”‘ Store server keys as environment variables in production
  • πŸ”„ Implement token refresh logic in onNewToken()
  • βœ… Validate notification payloads server-side
  • πŸ”’ Use HTTPS for all server communications

πŸ’‘ Pro Tips

Topic Naming

  • Use lowercase with hyphens: news-updates, sports-alerts
  • Avoid spaces and special characters
  • Keep names descriptive and meaningful

Production Checklist

  • Implement backend service for token management
  • Store tokens securely in database
  • Handle onNewToken() for token refresh
  • Add notification channels (Android 8.0+)
  • Implement analytics for delivery tracking
  • Test on multiple Android versions
  • Configure proper notification icons and colors

πŸ“š Learning Resources

🀝 Contributing

Contributions are welcome! Feel free to:

  • πŸ› Report bugs via Issues
  • ✨ Suggest new features
  • πŸ”§ Submit pull requests
  • πŸ“– Improve documentation

πŸ“„ License

This project is available for educational purposes. Feel free to use and modify.


Need Help? Check Stack Overflow or Firebase Community

Made with ❀️ using Kotlin & Jetpack Compose