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
- Create a Firebase Project:
- Go to the Firebase Console.
- Click on “Add Project” and follow the setup instructions.
- 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 theapp
directory of your Android project.
Adding Dependencies
In your project’s build.gradle
file, add the following dependencies:
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:
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:
apply plugin: 'com.google.gms.google-services'
Configuring FCM in Android
Create a service class that extends FirebaseMessagingService
to handle incoming messages:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
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
:
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Sending a Test Notification
- Go to the Firebase Afghanistan Phone Number List Console.
- Select your project and navigate to Cloud Messaging.
- Click on “Send your first message.”
- 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.