“`html
How to Add Push Notifications to an Android App: A Firebase Cloud Messaging Guide
Push notifications keep users engaged, and Firebase Cloud Messaging (FCM) is the simplest way to add them to Android. This guide covers setup, code, and testing with just Android Studio and a Firebase account.
Before starting, ensure you have Android Studio installed and a device or emulator running Android 4.1 or higher. Keep your app’s package name handy, as Firebase uses it to generate your configuration file.
1. Create a Firebase Project
Open the Firebase Console, click “Add Project,” and follow the prompts. Register your Android app with your package name, then download the generated google-services.json file and place it in your app module’s root directory.
2. Add Dependencies
Add the following to your Gradle files:
- Project-level build.gradle:
classpath 'com.google.gms:google-services:4.4.1' - App-level build.gradle: apply the Google Services plugin and add
implementation 'com.google.firebase:firebase-messaging:23.4.1'
Sync your project to apply the changes.
3. Create a Messaging Service
Create a class that extends FirebaseMessagingService. Override onMessageReceived to handle incoming payloads and display notifications with NotificationCompat.Builder. Also override onNewToken to capture refreshed device tokens.
4. Register and Ask Permission
Add the service to AndroidManifest.xml. On Android 13+, request the POST_NOTIFICATIONS permission at runtime using ActivityResultContracts.RequestPermission.
5. Send a Test Notification
In the Firebase Console, go to Messaging and click “Send your first message.” Enter a title and body, select your app, and send. The notification will appear instantly on your device.
Adding push notifications to Android is straightforward with FCM. Once the basics work, explore data messages, topics, and notification channels for richer user engagement.
“`