message
Mobile App Development

How to Implement Push Notifications in Android (with Code)

Blog bannerBlog banner

Push notifications are a powerful tool for engaging users and delivering real-time updates in Android apps. In this blog, we’ll walk you through how to set up and implement push notifications using Firebase Cloud Messaging (FCM).

Importance of Push Notifications & Their Impact on User Experience

Push notifications play a crucial role in enhancing user engagement and overall app experience. Here's how:

  1. Real-Time Communication:
    Push notifications allow apps to instantly inform users about important events like updates, offers, messages, or reminders, without them needing to open the app.
  2. Improved User Engagement:
    Timely and relevant notifications bring users back to the app, increasing retention and activity levels.
  3. Personalisation:
    Notifications can be tailored based on user behavior, preferences, or location, making the experience feel more relevant and personal.
  4. Boosts Conversions:
    For e-commerce, service, or booking apps, notifications about deals, abandoned carts, or limited-time offers often lead to higher conversion rates.
  5. Better User Retention:
    A well-designed notification strategy keeps users informed and involved, reducing app uninstalls and inactivity.
  6. Operational Efficiency:
    Notifications can be used for alerts (e.g., task updates, payment status, delivery tracking), helping users take timely action and improving satisfaction.

Step 1: Set Up Firebase Cloud Messaging (FCM)

1. Create a Firebase Project

  • Go to the Firebase Console.
  • Create a new project and register your Android app.

2. Add Firebase SDK

In your project-level build.gradle file:

Code

  buildscript {
      dependencies {
          classpath 'com.google.gms:google-services:4.4.2'
      }
  }
  
  In your app-level build.gradle:
  plugins {
      id 'com.android.application'
      id 'com.google.gms.google-services'
  }
  
  dependencies {
      // Firebase BoM
      implementation platform('com.google.firebase:firebase-bom:33.14.0')
  
      // Firebase Cloud Messaging
      implementation 'com.google.firebase:firebase-messaging'
  }      
      

3. Add google-services.json

  • Download google-services.json from Firebase and place it in your app’s root directory (app/).

Step 2: Configure Permissions and Notification Channels

AndroidManifest.xml

Code

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

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

Notification Channel (Android 8+)

Code

  fun createNotificationChannel(context: Context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            "default_channel",
            "Default Channel",
            NotificationManager.IMPORTANCE_DEFAULT
        )
        val manager = context.getSystemService(NotificationManager::class.java)
        manager?.createNotificationChannel(channel)
    }
  }          
      

Call this inside Application.onCreate().

Step 3: Receive and Handle Messages

Create a Firebase Messaging Service

Code

  class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d("FCM", "New token: $token")
        // Send this token to your server if needed
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        val title = remoteMessage.notification?.title ?: "Default Title"
        val message = remoteMessage.notification?.body ?: "Default Message"

        showNotification(title, message)
    }

    private fun showNotification(title: String, message: String) {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val notification = NotificationCompat.Builder(this, "default_channel")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .build()

        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(0, notification)
    }
  }          
      

Step 4: Send Push Notifications

Option 1: From Firebase Console

  • Go to Firebase Console > Cloud Messaging > Send your first message
  • Target your app and send!

Option 2: From Server (Using cURL or your backend)

Code

  curl -X POST -H "Authorization: key=YOUR_SERVER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "to": "YOUR_DEVICE_FCM_TOKEN",
      "notification": {
      "title": "Hello!",
      "body": "This is a test push notification"
      }
  }' https://fcm.googleapis.com/fcm/send             
      

Replace YOUR_SERVER_KEY with the one from Firebase > Project Settings > Cloud Messaging tab.

Step 5: Test and Debug

  • Use adb logcat | grep FCM to see logs.
  • Test with different Android versions to verify behavior.
  • Use Firebase Notifications Composer to send test messages easily.
Hire Now!

Hire Android App Developers Today!

Ready to bring your app vision to life? Start your journey with Zignuts expert iOS developers.

**Hire now**Hire Now**Hire Now**Hire now**Hire now

Best Practices

  • Always use notification channels for Android 8.0+.
  • Store the FCM token securely on your server.
  • Show in-app messages only if the user is not already on the relevant screen.
  • Use data-only messages if you want full control over behavior.

Conclusion

Integrating push notifications in Android with FCM is straightforward and powerful. Whether you're sending alerts, reminders, or messages, this setup ensures users stay engaged with your app.

card user img
Twitter iconLinked icon

Developer focused on creating user-friendly applications and improving system performance. Committed to continuous learning and helping others through technical writing.

card user img
Twitter iconLinked icon

Passionate developer with expertise in building scalable web applications and solving complex problems. Loves exploring new technologies and sharing coding insights.

Book a FREE Consultation

No strings attached, just valuable insights for your project

Valid number
Please complete the reCAPTCHA verification.
Claim My Spot!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Our Latest Blogs

View All Blogs