【发布时间】: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