首页 > 解决方案 > 如果应用程序未打开,Android 无法关闭通知

问题描述

我目前正在使用FirebaseMessagingService在我的 Android 应用程序上设置推送通知。我有一个非常简单的场景:

  1. 将向设备发送通知,其中包含以下内容:

    通知标题和正文,以及包含通知类型和一些预订 ID 的数据的 HashMap。

    以下是我在 Android 应用程序中提取这些数据的方法:

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        if (!remoteMessage.getData().isEmpty()) {
    
            Map<String, String> payload = remoteMessage.getData();
    
            String notificationType = payload.get("NOTIFICATION_TYPE");
            int bookingId = Integer.parseInt(payload.get("BOOKING_ID"));
            ...
        }
    
  2. 然后,我使用 switch 语句根据通知类型执行不同的操作:

    switch (notificationType){
                case "ALLOWED":    
                    createCheckinNotification(remoteMessage, bookingId);
                    break;
                case "HIDE_CANCEL":          
                case "MANUAL_CANCEL":   
                    Notification.dismissNotificationForBooking(getApplicationContext(), bookingId);
                    break;
            }
    

现在,当我打电话时,createCheckinNotification(remoteMessage, bookingId)我将 bookingId 保存在随机生成的通知 id 中:

SharedPreferences sharedPreferences = context.getSharedPreferences("bookings", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(String.valueOf(notification.bookingId), notification.id);
        editor.commit();

当我打电话时,Notification.dismissNotificationForBooking(getApplicationContext(), bookingId);我会检查共享首选项以获取通知 ID 以将其删除。

public static void dismissNotificationForBooking(Context context, int bookingId) {

    SharedPreferences sharedPreferences = context.getSharedPreferences("bookings", Context.MODE_PRIVATE);
    String bookingIdString = String.valueOf(bookingId);

    int notificationId = sharedPreferences.getInt(bookingIdString, -1);
    if (notificationId != -1){
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(notificationId);
    }
}

现在,当应用程序运行时,此代码可以正常工作。但是,当应用程序未运行或在后台关闭通知永远不会工作,我不知道为什么。也因为应用程序没有运行我在调试应用程序时遇到了麻烦。

编辑 1 我使用文件资源管理器检查了共享首选项,当应用程序不在前台时,数据似乎没有保存到共享首选项中,但在应用程序打开时保存得很好

编辑 2 当我的签入代码运行时,我在共享首选项中添加了一个测试值,其中包含以下内容:

 SharedPreferences sharedPreferences = context.getSharedPreferences("bookings", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("teststring", "value");
            editor.commit();

当应用程序在后台/未运行时,永远不会添加此值。似乎与我的通知 ID 相同的问题。如果应用程序在后台运行,则不会将其添加到共享首选项中,因此当我们尝试关闭通知时,共享首选项中保存的 bookingId 没有值

标签: androidfirebasepush-notificationfirebase-cloud-messaging

解决方案


推荐阅读