代码之家  ›  专栏  ›  技术社区  ›  Mwikala Kangwa

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

  •  0
  • Mwikala Kangwa  · 技术社区  · 6 年前

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

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

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

    存储布尔值:

    // 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 回复  |  直到 6 年前
        1
  •  1
  •   cutiko    6 年前

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

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

    推送消息有3种类型:通知、数据,以及两者;

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

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

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

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

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

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

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

        2
  •  0
  •   Mwikala Kangwa    6 年前

    不管你做什么 Firebase 必须重写应用程序中设置的内容。我发现这一点,不是从Firebase控制台发送,而是从web服务器发送通知。通知已完全停止,共享首选项也正常工作。

        3
  •  0
  •   blast king    6 年前
     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){
    
         }