在SharedPreference保存应用程序范围布尔(Save Application Wide

2019-10-29 11:47发布

我知道,这是经常问的一个问题,我花了整个下午都尝试不同的解决方案,似乎并没有工作。

我想存储一个布尔receiveNotifications在SharedPreferences但是当我发送通知仍然来通过。 当我检查布尔是否是我设置的活动设置,它说,该值是应该的,但是当我把这个在我的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);
}

Answer 1:

推送消息是一个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":{
    }
  }

每个将在应用程序取决于该应用是否打开或不会触发不同的行为。

  • 通知:如果应用程序是开放的服务的代码会被执行,如果没有通知被默认显示

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

  • 两个:F应用程序是开放的服务的代码会被执行,如果没有通知被默认显示和数据将在发射活动可以作为额外的意图得到

在火力地堡Web控制台会一直发出“通知”类型,如果你添加数据,自订参数会同时发送。

你的布尔永远不会考虑采取如果应用程序被关闭,并通知来自Web的控制台。



Answer 2:

事实证明,无论你做什么Firebase必须覆盖不管你在应用程序中已设置。 我发现这一点的,而不是从火力地堡控制台发送,我发送的通知,从我的网络服务器。 该通知是完全停止共享偏好的工作。



Answer 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){

     }


文章来源: Save Application Wide Boolean in SharedPreference