【问题标题】:Issue with boolean on shared preferences共享首选项的布尔值问题
【发布时间】:2012-08-04 15:15:54
【问题描述】:

我目前正在尝试在手机启动时根据布尔值 false 或 true 启动服务。问题是如果我使用 getBoolean

 boolean isPhysicalSirenFlagged = sp.getBoolean("isPhysicalSirenFlagged", true);
 boolean isSMSSirenFlagged = sp.getBoolean("isSMSSirenFlagged", true);

每当手机启动时,它们都会设置为 true,导致我的 isPhysicalSirenFlagged 和 isSMSSirenFlagged 都为 true。是否可以检查一个值的当前布尔值是什么?

代码:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     String value = sp.getString("serial", "");
     boolean isPhysicalSirenFlagged = sp.getBoolean("isPhysicalSirenFlagged", true);
     boolean isSMSSirenFlagged = sp.getBoolean("isSMSSirenFlagged", true);

     if (isPhysicalSirenFlagged) {
         //true
         Intent physicaldialog = new Intent(context, PhysicalTheftDialog.class);
         physicaldialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(physicaldialog);
         context.startService(new Intent(context, PhysicalTheftService.class));
     }
     else {
         //false
     }

     if (isSMSSirenFlagged) {
         //true
         Intent smsdialog = new Intent(context, SMSNotificationPasswordDialog.class);
         smsdialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(smsdialog);
         context.startService(new Intent(context, RemoteSirenService.class));
     }
     else {
         //false
     }

【问题讨论】:

  • 我不明白你的问题。如果将它们设置为 false,则它们将为 false。
  • 是的,这就是为什么我想知道而不是将它们设置为 false 的原因,有没有办法只检查可能 isSMSSIrenFlagged 的​​当前布尔值?因为无论手机何时启动,getBoolean 语句都会被执行
  • @dythe 没有*。这就是为什么有一个默认值(你作为第二个参数传入的 true)。
  • 我无法理解您的问题。您正在尝试在手机启动时启动服务。因此,当您的手机启动时,您可以不使用任何布尔值。否则,如果您在应用程序中提供了任何设置,则按值工作。这有什么问题?注意:要检查sharedpreference 中的默认值,需要传递一个默认值,而您已经在传递true
  • 对不起。我仍然不明白您的问题..也许下面提供的答案可以帮助..如果没有,请尝试更好地解释。什么是SMSSirenFlagged?谁把它设置成什么?因为如果 isSMSSirenFlagged 在共享首选项中不存在,您将传递默认值“true”,它将被标记为 true...

标签: android boolean sharedpreferences


【解决方案1】:

改为将其设置为 false,显然您所做的并不是对 SharedPrefereces 进行更改以指示标志。通过使用 false 作为默认值,您将防止对标志的意外 true 分配。老实说,您应该使用 int 标志(或首选枚举)来表示这一点。这是确定设备所处状态的一种更安全的方法。例如:

int NO_STATE    = 0
int IS_THEFTED  = 1
int IS_WAILING  = 2

or

enum State {
    NONE, THEFTED, WAILING;
}

【讨论】:

  • 同意,试试:sp.getBoolean('key', false);
猜你喜欢
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2017-01-28
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多