You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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 the google-services.json file and place it in the app/ 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
      }
      
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 MyFirebaseMessagingService class that extends FirebaseMessagingService:
    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-tools in 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.js and write a function that listens to your database changes. Example for Firestore:
    const 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;
        });
    
    For Realtime Database, use 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 data field in the payload instead of notification if you need to process background data in your app, not just show a visible alert.

内容的提问来源于stack exchange,提问作者Harshita Ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:47:40