有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在SharedReference中保存应用程序范围的布尔值

我知道这是一个常见的问题,我整个下午都在尝试各种似乎不起作用的解决方案

我试图在SharedReferences中存储布尔值receiveNotifications,但当我发送通知时,它仍然会通过。当我检查是否在我设置它的活动中设置了布尔值时,它表示该值是它应该的值,但是当我在我的FirebaseMessagingService中调用它时,它仍然允许通过通知

这是我第一次使用它们,所以如果你看到明显的答案,那就是原因

存储布尔值:

// shared preferences
notificationsPref = mContext.getSharedPreferences("notifications", MODE_PRIVATE);
SharedPreferences.Editor editor = notificationsPref.edit();
                editor.putBoolean("receiveNotifications", false);
                editor.apply();

检查是否设置了布尔值:

// check if they want to receive notifications
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("notifications", MODE_PRIVATE);
Boolean areNotificationsAllowed = sharedPreferences.getBoolean("receiveNotifications", true);
if (areNotificationsAllowed){
        Toast.makeText(this, "Send Notification", Toast.LENGTH_SHORT).show();
        sendNotification(contentTitle, messageBody);
}

共 (3) 个答案

  1. # 1 楼答案

    结果表明,无论您做什么Firebase都必须覆盖您在应用程序中设置的内容。我不是从Firebase控制台发送,而是从web服务器发送通知,从而发现了这一点。通知完全停止了,共享首选项也正常工作

  2. # 2 楼答案

    推送消息是一个Json对象,下一个示例直接来自文档:

    {
      "message":{
        "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
        "notification":{
          "title":"Portugal vs. Denmark",
          "body":"great match!"
        }
      }
    }
    

    推送消息有三种类型:通知、数据和两者

      //Notification
      "message":{
        "notification":{
        }
      }
    
      //data
      "message":{
        "data":{
        }
      }
    
      //both
      "message":{
        "notification":{
        },
        "data":{
        }
      }
    

    根据应用是否打开,每个应用都会在应用中触发不同的行为

    • 通知:如果应用程序已打开,则将执行服务上的代码,如果未打开,则默认显示通知

    • 数据:将始终执行服务上的代码

    • 两者:如果应用程序已打开,则将执行服务上的代码,如果未打开,则默认情况下会显示通知,并且数据将在启动器活动中作为可从intent获得的额外数据提供

    Firebase web控制台将始终发送“通知”类型,如果您将数据添加为自定义参数,它将同时发送这两种类型

    如果应用程序关闭且通知来自web控制台,则永远不会考虑您的布尔值

  3. # 3 楼答案

     private SharedPreferences prefs;
     private SharedPreferences.Editor editor;
    
    
     prefs = getApplicationContext().getSharedPreferences("notifiactions", 
     MODE_PRIVATE);
    
     editor = prefs.edit();
    
     /////Assigning a Boolean///////////
    
    editor.putBoolean("receiveNotifications", false);
    editor.commit();
    
    //Retrieving Boolean
     prefs = getApplicationContext().getSharedPreferences("notifications", 
     MODE_PRIVATE);
     bool = prefs.getBoolean("receiveNotifications", true);
    
       //Try replacing this with your code also
         if(bool){
    
         }