如何通过Firebase实现Web API向Android App推送数据库变更通知?
Hey there! Let's walk through exactly how to set up Firebase Cloud Messaging (FCM) to send push notifications to your Android app whenever your web app's database changes. I've broken this down into actionable, easy-to-follow steps:
1. Set Up Your Firebase Project & Configure the Android App
First, link your Android app to a Firebase project:
- Head to the Firebase Console, create a new project (or use an existing one if you have it).
- Add your Android app to the project: Enter your app's exact package name (must match what's in your
AndroidManifest.xml), then download thegoogle-services.jsonfile and place it in theapp/directory of your Android project. - Update your Android build files:
- In your project-level build.gradle, add the Firebase classpath:
dependencies { classpath 'com.google.gms:google-services:4.3.15' // Use the latest version available } - In your app-level build.gradle, apply the Firebase plugin at the bottom and add the FCM dependency:
apply plugin: 'com.google.gms.google-services' dependencies { implementation 'com.google.firebase:firebase-messaging:23.4.0' // Latest version recommended }
- In your project-level build.gradle, add the Firebase classpath:
2. Implement FCM Functionality in Your Android App
Next, get your app ready to receive notifications and send its device token to your database:
- Create a
MyFirebaseMessagingServiceclass that extendsFirebaseMessagingService:class MyFirebaseMessagingService : FirebaseMessagingService() { override fun onMessageReceived(remoteMessage: RemoteMessage) { // Handle incoming notification remoteMessage.notification?.let { showNotification(it.title, it.body) } } override fun onNewToken(token: String) { // Send this token to your web app's database // Use your web API or direct database write to store it (linked to the user/device) Log.d("FCM_TOKEN", "New token: $token") } private fun showNotification(title: String?, body: String?) { val intent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) val notificationBuilder = NotificationCompat.Builder(this, "CHANNEL_ID") .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setContentIntent(pendingIntent) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Create notification channel for Android 8.0+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel("CHANNEL_ID", "App Notifications", NotificationManager.IMPORTANCE_DEFAULT) notificationManager.createNotificationChannel(channel) } notificationManager.notify(0, notificationBuilder.build()) } } - Register this service in your
AndroidManifest.xml:<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> - For Android 13+, add the notification permission to your manifest and request it in your activity:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
3. Set Up Cloud Functions to Trigger Notifications on Database Changes
This is the core part—using Firebase Cloud Functions to listen for database changes and send notifications:
- Install the Firebase CLI: Run
npm install -g firebase-toolsin your terminal. - Log in to Firebase:
firebase login - Initialize Cloud Functions in your project directory:
firebase init functions(select JavaScript/TypeScript, enable ESLint if you want) - Open
functions/index.jsand write a function that listens to your database changes. Example for Firestore:
For Realtime Database, useconst functions = require("firebase-functions"); const admin = require("firebase-admin"); admin.initializeApp(); // Trigger when a document is created/updated in your collection exports.sendNotificationOnDbChange = functions.firestore .document("your-collection/{docId}") .onWrite(async (change, context) => { // Fetch the target user's FCM token from your database const userDoc = await admin.firestore().collection("users").doc("target-user-id").get(); const fcmToken = userDoc.data().fcmToken; if (!fcmToken) { functions.logger.error("No FCM token found for user"); return null; } // Define the notification payload const payload = { notification: { title: "Database Updated!", body: "A change was made to your web app's database." }, token: fcmToken }; // Send the notification try { await admin.messaging().send(payload); functions.logger.info("Notification sent successfully"); } catch (error) { functions.logger.error("Error sending notification:", error); } return null; });functions.database.ref("your-path/{nodeId}").onWrite(...)instead. - Deploy the function: Run
firebase deploy --only functions
4. Test the End-to-End Flow
- Ensure your Android app is installed on a device/emulator, and the FCM token has been saved to your database.
- Make a change to your web app's database (via your web app or directly in the Firebase Console).
- Check if your Android app receives the notification. If not, debug with Cloud Functions logs:
firebase functions:log
Quick Tips
- Always update the FCM token in your database when it changes (handled in
onNewToken)—tokens can expire or change when the app is reinstalled. - Link FCM tokens to specific users in your database to send targeted notifications for relevant changes.
- Use the
datafield in the payload instead ofnotificationif you need to process background data in your app, not just show a visible alert.
内容的提问来源于stack exchange,提问作者Harshita Ghosh
相关产品推荐
相关产品推荐

