在Android中,当应用程序处于后台或被关闭时,如Facebook应用程序一样在接收通知时设置应用程序图标上的徽章编号。

5

我正在使用React Native为Android和iOS开发应用程序。当我收到远程通知时,我想在应用程序图标上显示徽章数字。我正在使用第三方库React-Native-FCM,并且iOS的徽章可以正常工作。在Android上,只有在应用程序处于前台时才能显示徽章数字。当应用程序被杀死或处于后台时,我无法显示徽章数字。我知道Android不支持本地显示徽章,但我已经看到Facebook和Messenger应用程序在Android上显示徽章。请问有人能告诉我如何在Android上实现这一点,即使应用程序被杀死或处于后台也能显示徽章?提前感谢。


我昨天才在应用程序图标上实现了徽章数字显示,但我正在使用 FCM。 - Avinash
我正在使用 https://github.com/leolin310148/ShortcutBadger 库来在应用图标上显示徽章。 - Avinash
是的,react-native-fcm 也使用 FCM 服务。问题在于当应用程序被杀死或处于后台时,onMessageReceived 不会被调用。 - Zwe
只给我10分钟,我会回答的。 - Avinash
请看我的回答,这里 public void zzm(Intent intent) 会在应用程序处于后台或已关闭时始终被调用。 - Avinash
1个回答

3

onMessageReceived方法不会被调用,它只会被数据负载所调用。

即使发送了数据负载和通知负载,onMessageReceived也不会被调用。

当应用程序在后台或已关闭时,使用以下代码从服务器获取徽章,因为您的FirebaseMessagingService正在运行。

public class Custom_FirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FirebaseMsgService";
    String activityName;

    @Override
    public void zzm(Intent intent) {
        Log.i("uniqbadge", "zzm");
        Set<String> keys = intent.getExtras().keySet();
        for (String key : keys) {
            try {
                 Log.i("uniq", " " + key + " " + intent.getExtras().get(key));
                if (key.equals("badge")) {
                    String cnt = intent.getExtras().get(key).toString();
                    int badgeCount = Integer.valueOf(cnt);
                    Log.i("uniq", " badge count " + badgeCount);
                    ShortcutBadger.applyCount(this, badgeCount);
                    Log.i("uniq", " " + "end");
                }
            } catch (Exception e) {
                Log.i("uniqbadge", "zzm Custom_FirebaseMessagingService" + e.getMessage());
            }
        }

        super.zzm(intent);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        if (remoteMessage.getNotification() != null) {
            Log.i(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());

        }
        if (remoteMessage.getData().size() > 0) {
            Log.i(TAG, "Data Payload: " + remoteMessage.getData().toString());
            ...

2
@Avi,当我在我的项目中进行测试时,出现错误,方法zzm无法被覆盖。 - BatyrCan
@Avinash 我也是一样。zzm 无法被覆盖。 - Manu Ram V

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接