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

Android应用基于Firebase实现用户通知接收偏好设置方案咨询

Hey there! Let's walk through how to implement user-controlled notification opt-in for your FCM-powered app, so you only send alerts to users who've chosen to receive them. Here's a detailed, step-by-step breakdown:

1. Client-Side Implementation

First, we need to give users control over their notification preferences and sync that choice with your backend.

  • Add a Notification Toggle UI
    Add a switch/toggle button in your app's settings screen (or any prominent, easy-to-find place) labeled something like "Enable Push Notifications". This is the user's direct control point for opting in or out.

  • Store the Preference Locally
    Use your app's local storage (like SharedPreferences on Android, UserDefaults on iOS) to persist the user's choice. Example for Android:

    // Save preference when user toggles the switch
    val sharedPref = context.getSharedPreferences("app_settings", Context.MODE_PRIVATE)
    sharedPref.edit().putBoolean("notifications_enabled", switch.isChecked).apply()
    
    // Retrieve the preference on app launch
    val isNotificationsEnabled = sharedPref.getBoolean("notifications_enabled", true) // Default to enabled
    
  • Manage FCM Token Based on Preference

    • When user opts in: If they enable notifications, fetch the current FCM token (if not already stored) and send it to your backend to mark as an "active" token.
    • When user opts out: Call the FCM token deletion method, then notify your backend to mark that token as inactive or remove it entirely. Example for Android:
      FirebaseMessaging.getInstance().deleteToken()
          .addOnCompleteListener { task ->
              if (task.isSuccessful) {
                  // Call your backend API to disable/remove this token
                  disableTokenOnBackend()
              }
          }
      
  • Handle Token Refresh Events
    FCM tokens can refresh automatically. Make sure to listen for the onNewToken callback and update your backend with the new token—while preserving the user's opt-in status:

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        val isEnabled = sharedPref.getBoolean("notifications_enabled", true)
        if (isEnabled) {
            uploadTokenToBackend(token)
        } else {
            // Optionally upload the new token but mark it as disabled
            uploadDisabledTokenToBackend(token)
        }
    }
    
2. Backend Setup

Your backend needs to track which tokens are active (opt-in) to filter notifications correctly.

  • Create a Token Registry
    Set up a database table to store user FCM tokens along with their opt-in status. Example SQL schema:

    CREATE TABLE user_fcm_tokens (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id VARCHAR(255) NOT NULL,
        fcm_token VARCHAR(255) NOT NULL UNIQUE,
        is_enabled BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    );
    
  • Update Token Status
    Build API endpoints that your client can call to enable/disable tokens. For example:

    • POST /api/tokens/enable to mark a token as active
    • POST /api/tokens/disable to mark a token as inactive
  • Filter Tokens Before Sending Notifications
    Whenever you want to send a bulk notification, query your database to fetch only tokens where is_enabled = true, then send the FCM message to this filtered list. Example using Firebase Admin SDK (Java):

    // Fetch all enabled tokens from your DB
    List<String> activeTokens = tokenRepository.findByIsEnabled(true);
    
    // Build and send the multicast message
    MulticastMessage message = MulticastMessage.builder()
        .setNotification(Notification.builder()
            .setTitle("New Alert")
            .setBody("You have a new update!")
            .build())
        .addAllTokens(activeTokens)
        .build();
    
    BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
    
3. FCM Console Workaround

If you occasionally use the FCM Console to send notifications, note that it doesn't support filtering tokens directly. Instead:

  • Export the list of active tokens from your database
  • Use the "Multiple devices" option in the Console and paste the active tokens to target only opted-in users
4. Edge Cases to Cover
  • App Reinstall: When a user reinstalls the app, default the notification preference to enabled (or sync it with their user account if you have cloud storage for preferences).
  • Clear App Data: Local preferences will be lost, so again, default to enabled or prompt the user to re-set their choice.
  • Token Expiry: FCM tokens can expire—your backend should handle failed delivery attempts (from FCM responses) and mark invalid tokens as inactive.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:41:06