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

如何通过Firebase群组消息发送推送通知?高校Android作业通知实现求助

Hey there! I’ve built similar college app features before, so let’s walk through both your requirements clearly.

实现教师选择课程并发送作业通知的功能

Let’s start with the core feature flow: teacher selects their course → creates an assignment → sends notifications to enrolled students.

Step 1: Design Your Data Structure (Firebase-First Approach)

Since you’re using Firebase for push notifications, it makes sense to use Firestore/Realtime Database for your core data. Here’s a clean structure:

  • users collection: Each document stores userId, role (teacher/student), enrolledCourses (array of course IDs), and fcmToken (for push notifications).
  • courses collection: Each document has courseId, courseName, teacherId, enrolledStudentIds (array of user IDs), and fcmGroupId (we’ll use this for group pushes later).
  • assignments collection: Each document includes assignmentId, courseId, title, description, dueDate, and postedBy (teacher ID).

Step 2: Build the Teacher’s Course Selection UI

Show only the courses the logged-in teacher owns using a RecyclerView. Here’s a quick Firestore query example in Kotlin:

val currentTeacherId = FirebaseAuth.getInstance().currentUser?.uid ?: return
val db = FirebaseFirestore.getInstance()

db.collection("courses")
    .whereEqualTo("teacherId", currentTeacherId)
    .get()
    .addOnSuccessListener { snapshot ->
        val teacherCourses = snapshot.toObjects(Course::class.java)
        // Populate your RecyclerView adapter with this list
        courseRecyclerView.adapter = CourseAdapter(teacherCourses) { selectedCourse ->
            // Navigate to assignment creation screen with the selected course
            navigateToAssignmentCreator(selectedCourse)
        }
    }

Step 3: Handle Assignment Creation & Notification Trigger

Once the teacher fills out the assignment details:

  1. Save the assignment to the assignments collection.
  2. Fetch the selected course’s fcmGroupId (we’ll set this up in the next section).
  3. Trigger the Firebase group push notification to all enrolled students.
使用Firebase群组消息发送推送通知

FCM group messaging is perfect for this use case—you can send one notification to all students in a course without iterating over individual tokens.

Step 1: Pre-Requisites

Make sure you’ve:

  • Added Firebase Cloud Messaging (FCM) to your Android project (included in the Firebase BoM).
  • Saved each student’s FCM token to their users document when they log in/app starts (tokens can change, so update them regularly).

Step 2: Create a Course-Specific FCM Group

You’ll want a unique group for each course. Create it when the course is first set up, or when the first student enrolls. Use the Firebase Admin SDK (run this on your backend or use Firebase Cloud Functions) to avoid exposing sensitive operations on the client:

// Firebase Admin SDK code (Java example)
String courseId = "your_course_id";
List<String> studentTokens = new ArrayList<>();
// Fetch all enrolled students' FCM tokens from the users collection

FirebaseMessaging.getInstance()
    .createGroup("group_course_" + courseId, studentTokens)
    .addOnSuccessListener(groupResponse -> {
        // Save the group ID to the course document
        FirebaseFirestore.getInstance()
            .collection("courses")
            .document(courseId)
            .update("fcmGroupId", groupResponse.getGroupId());
    });

Step 3: Send the Assignment Notification to the Group

When the teacher publishes an assignment, fetch the course’s fcmGroupId and send the notification:

// Kotlin client-side (or use Cloud Functions for better security)
val courseFcmGroupId = selectedCourse.fcmGroupId ?: return
val notification = Notification.builder()
    .setTitle("新作业提醒")
    .setBody("${selectedCourse.courseName}: ${assignmentTitle}已发布")
    .setImage("optional_assignment_preview_url")
    .build()

val message = Message.builder()
    .setNotification(notification)
    .setToken(courseFcmGroupId) // Use the group ID instead of individual tokens
    .build()

FirebaseMessaging.getInstance().send(message)
    .addOnSuccessListener {
        // Show success toast to the teacher
        Toast.makeText(context, "作业通知已发送", Toast.LENGTH_SHORT).show()
    }

Step 4: Update Group Members

When students enroll or drop the course, update the FCM group:

// Add a student to the group
FirebaseMessaging.getInstance().addToGroup(courseFcmGroupId, listOf(newStudentFcmToken))

// Remove a student from the group
FirebaseMessaging.getInstance().removeFromGroup(courseFcmGroupId, listOf(leavingStudentFcmToken))

Key Notes

  • Security Rules: Lock down your Firestore rules so teachers can only access their own courses, and students can only see their enrolled courses. Example rule for courses:
    allow read, write: if request.auth != null && request.auth.uid == resource.data.teacherId;
    
  • Notification Handling: Set up a FirebaseMessagingService in your Android app to handle incoming notifications, and configure a PendingIntent to open the assignment details screen when tapped.
  • Offline Support: FCM will queue notifications for students who are offline, so they’ll get it when they come back online.

内容的提问来源于stack exchange,提问作者Hamdan Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:24:58