You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Flutter应用终止状态下通知角标数量控制方法咨询

Hey there! Let's tackle this problem step by step since you're working with Flutter and don't have much Kotlin experience. Controlling app icon badge counts when your app is terminated and receives a notification is platform-specific, so we'll break down Android and iOS separately.

Android Implementation

Android doesn't have a system-wide standard for app badges—each manufacturer (Xiaomi, Huawei, Samsung, etc.) uses its own API. That means we need to handle these differences, either with a Flutter plugin or simplified Kotlin code (don't worry, I'll keep the Kotlin part straightforward).

Option 1: Use a Flutter Plugin (Easier for Kotlin Newbies)

The flutter_app_badger plugin wraps native badge logic for most major Android brands. Here's how to set it up:

  1. Add the dependency to your pubspec.yaml:
    dependencies:
      flutter_app_badger: ^1.5.0
    
  2. Important: When your app is terminated, Flutter's Dart code won't run. So you still need a tiny bit of Kotlin to handle badge updates when notifications arrive. Here's a simplified FirebaseMessagingService implementation (assuming you're using Firebase Cloud Messaging):
    import com.google.firebase.messaging.FirebaseMessagingService
    import com.google.firebase.messaging.RemoteMessage
    import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingService
    import me.leolin.shortcutbadger.ShortcutBadger // Add this library for broader support
    
    class MyFirebaseMessagingService : FlutterFirebaseMessagingService() {
        override fun onMessageReceived(remoteMessage: RemoteMessage) {
            super.onMessageReceived(remoteMessage)
            
            // Pull the badge count from your notification data (or hardcode for testing)
            val badgeCount = remoteMessage.data["badge"]?.toInt() ?: 1
            
            // Update the badge using ShortcutBadger (supports most Android brands)
            ShortcutBadger.applyCount(this, badgeCount)
        }
    }
    
  3. Add the ShortcutBadger dependency to your Android build.gradle (Module level):
    dependencies {
        implementation 'me.leolin:ShortcutBadger:1.1.22@aar'
    }
    
  4. Register the 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>
    

Option 2: Manual Manufacturer-Specific Code (If You Avoid Plugins)

If you don't want to use a plugin, you can write code for individual brands, but this is more maintenance-heavy. For example, here's how to handle Xiaomi devices:

try {
    val miuiNotificationClass = Class.forName("android.app.MiuiNotification")
    val field = miuiNotificationClass.getField("extraNotification")
    val extraNotification = field.get(null)
    val method = extraNotification.javaClass.getMethod("setBadgeCount", Int::class.java)
    method.invoke(extraNotification, badgeCount)
} catch (e: Exception) {
    // Fallback for other brands or errors
}

iOS Implementation

iOS has built-in support for app badges, so this is much simpler:

  1. When sending notifications via APNs (or Firebase Cloud Messaging), include the badge field in your payload. For example:
    {
      "aps": {
        "alert": "Your new notification",
        "badge": 2,
        "sound": "default"
      }
    }
    
    The iOS system will automatically update the app icon badge when the notification arrives—even if your app is terminated.
  2. When the user opens your app, don't forget to reset the badge count. You can do this with the flutter_app_badger plugin in Dart:
    import 'package:flutter_app_badger/flutter_app_badger.dart';
    
    void resetBadge() async {
      await FlutterAppBadger.removeBadge();
    }
    

Key Takeaways

  • Android: Since there's no universal API, rely on libraries like ShortcutBadger to cover most manufacturers. You need native Kotlin code to handle badge updates when the app is terminated (Dart code won't run then).
  • iOS: Let the system handle it by including the badge field in your notification payload. Just remember to reset the badge when the app opens.
  • Flutter Plugins: flutter_app_badger simplifies cross-platform badge management, but Android still needs that small native code snippet for terminated state handling.

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

火山引擎 最新活动