如何从Node.js服务器向Android客户端发送通知?所需技术咨询
Hey Anna! Since you're new to Node.js, let's walk through exactly how to send notifications from your Node.js server to an Android client—specifically that friend request scenario where User B gets alerted when User A sends a request. I'll break this down into easy-to-follow steps with practical code examples.
Building your own long-connection system (like WebSockets) from scratch is doable but way more complex for beginners. Instead, use a managed push service. The best choice for Android is Firebase Cloud Messaging (FCM)—it's free, Google-official, and integrates seamlessly with Android apps.
1. Set Up FCM Credentials
First, you need to get the necessary keys for both your Android app and Node.js server:
- Go to the Firebase Console, create a new project, and add an Android app to it. Download the
google-services.jsonfile (you'll need this for your Android project). - In the Firebase Console, navigate to Project Settings > Cloud Messaging, and copy the Server Key (under Cloud Messaging API (Legacy)). Also, download the Service Account Key (a JSON file) for your Node.js server to authenticate with FCM.
2. Configure the Android Client
Your Android app needs to:
- Integrate FCM SDK: Add these dependencies to your app-level
build.gradle:implementation 'com.google.firebase:firebase-messaging:23.4.0' // Use the latest version - Get and Send Device Token: When the app starts, fetch the unique FCM token for the device, then send this token to your Node.js server and store it in your database (linked to User B's account). Here's a quick code snippet:
FirebaseMessaging.getInstance().token.addOnCompleteListener { task -> if (!task.isSuccessful) { Log.w("FCM", "Fetching FCM registration token failed", task.exception) return@addOnCompleteListener } // Get new FCM registration token val token = task.result // Send this token to your Node.js server via API sendTokenToServer(token) } - Handle Incoming Notifications: Create a class extending
FirebaseMessagingServiceto handle notifications when they arrive:
Don't forget to register this service in yourclass MyFirebaseMessagingService : FirebaseMessagingService() { override fun onMessageReceived(remoteMessage: RemoteMessage) { // Create and show a notification in the status bar remoteMessage.notification?.let { showNotification(it.title!!, it.body!!) } } 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 notification = NotificationCompat.Builder(this, "friend_request_channel") .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(body) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .build() NotificationManagerCompat.from(this).notify(1, notification) } }AndroidManifest.xml.
3. Implement Notification Logic in Node.js Server
Now, set up your Node.js server to send notifications via FCM:
Install Dependencies: Use Firebase's official admin SDK for Node.js:
npm install firebase-adminInitialize Firebase Admin: Use the service account key you downloaded earlier:
const admin = require('firebase-admin'); const serviceAccount = require('./path/to/your-service-account-key.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: 'https://your-firebase-project-id.firebaseio.com' });Write a Notification Sender Function: This function will take the target user's FCM token and the notification content, then send it via FCM:
async function sendFriendRequestNotification(targetToken, senderName) { const message = { notification: { title: "New Friend Request", body: `${senderName} wants to add you as a friend!` }, token: targetToken }; try { const response = await admin.messaging().send(message); console.log('Notification sent successfully:', response); } catch (error) { console.error('Failed to send notification:', error); } }Trigger the Notification on Friend Request: When User A submits a friend request, your server should:
- Save the request to your database (e.g., MongoDB, PostgreSQL).
- Look up User B's stored FCM token from the database.
- Call the notification function to send the alert.
Example with Express.js:
const express = require('express'); const app = express(); app.use(express.json()); // Assume you have a database connection set up const db = require('./your-db-connection'); app.post('/send-friend-request', async (req, res) => { const { senderId, receiverId } = req.body; // 1. Save friend request to DB await db.collection('friendRequests').insertOne({ senderId, receiverId, status: 'pending', createdAt: new Date() }); // 2. Fetch receiver's FCM token from DB const receiver = await db.collection('users').findOne({ userId: receiverId }); const targetToken = receiver.fcmToken; // 3. Fetch sender's name for the notification const sender = await db.collection('users').findOne({ userId: senderId }); const senderName = sender.fullName; // 4. Send the notification await sendFriendRequestNotification(targetToken, senderName); res.status(200).json({ message: 'Friend request sent!' }); }); app.listen(3000, () => console.log('Server running on port 3000'));
- Token Updates: FCM tokens can change (e.g., when the user reinstalls the app or gets a new device). Make sure your Android app listens for token updates and sends the new token to your server to keep your database up-to-date.
- Background vs. Foreground: If the Android app is in the background, FCM will automatically show the notification in the status bar. If you need to handle custom logic when the app is open, use data messages instead of notification messages.
- Alternatives: If you don't want to use FCM, OneSignal is another popular cross-platform push service. But FCM is the most straightforward for Android-only apps.
内容的提问来源于stack exchange,提问作者anna

