Notification Firebase Android Example

Firebase Cloud Messaging (FCM) is a powerful service provided by Google that allows Notification Firebase  developers to send notifications and messages to users on various platforms, including Android. This article provides an example of how to implement notifications in an Android application using Firebase.

Setting Up Firebase

  1. Create a Firebase Project:
    • Go to the Firebase Console.
    • Click on “Add Project” and follow the setup instructions.
  2. Add Firebase to Your Android App:
    • In the Firebase BTC Users Number Console, add your Android app by providing the package name.
    • Download the google-services.json file and place it in the app directory of your Android project.

Adding Dependencies

In your project’s build.gradle file, add the following dependencies:

groovy

dependencies {
implementation 'com.google.firebase:firebase-messaging:23.0.0'
}

Also, add the Google services classpath to the build.gradle file at the project level:

groovy

buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.8'
}
}

Apply the Google services plugin at the bottom of the build.gradle file in the app module:

groovy

apply plugin: 'com.google.gms.google-services'

Configuring FCM in Android

Create a service class that extends FirebaseMessagingService to handle incoming messages:

java

public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle the received message
showNotification(remoteMessage.getNotification().getBody());
}

private void showNotification(String messageBody) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}

Register your service in the AndroidManifest.xml:

xml

<service
android:name=".MyFirebaseMessagingService"
android:exported="false">

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

Sending a Test Notification

  1. Go to the Firebase Afghanistan Phone Number List Console.
  2. Select your project and navigate to Cloud Messaging.
  3. Click on “Send your first message.”
  4. Enter the notification details and select your app.

Conclusion

This article explained how to set up Firebase Cloud Messaging in an Android app and handle notifications. By following these steps, you can implement robust notification functionality in your application, ensuring timely and effective communication with your users.