在Android中为通知设置震动、闪光或声音的组合

7
我想为用户提供选择“灯光”、“声音”或“振动”或这三种方式的组合,以便在“通知”上进行警报。
在Android文档中,我看到了一个名为“DEFAULT_ALL”的选项,其中将使用所有3种警报方法。
否则,可以选择其中任何一种(“DEFAULT_LIGHTS”,“DEFAULT_VIBRATE”,“DEFAULT_SOUND”)。
是否有办法制作例如“SOUND”和“VIBRATION”但没有“LIGHTS”和其他组合的组合?
编辑
“Notification.Builder”的方法“setDefaults(int default)”(来自prolink007的答案)说:
值应该是以下字段之一或多个字段与按位或组合:DEFAULT_SOUND、DEFAULT_VIBRATE、DEFAULT_LIGHTS。
如何使用它?
5个回答

20

Notification.Builder API 11NotificationCompat.Builder API 1 提供几种方法来设置这些类型的警报。

  • setLights(...)
  • setSound(...)
  • setVibrate(...)

值应该是以下字段之一或多个按位或组合:DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS。

未经测试,但我认为如果您想要SOUNDVIBRATIONLIGHTS,则可以执行此操作:

setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE | DEFAULT_LIGHTS);

@Ashwin 我编辑了我的答案,并提供了更多关于你的第二个问题的信息。 - prolink007
@Ashwin,你的灯亮着吗?因为在三星Galaxy Ace上它们不工作。 - Gaurav Agarwal
@codingcrow:不,灯光不起作用(声音和振动正常工作)。我也有一部三星Ace手机。但我还在三星Galaxy Note上测试过,结果也是不起作用。这个问题困扰了我已经两个星期了。 - Ashwin

5

为了可移植性,我更喜欢使用NotificationCompat
用户可能会偏好他/她的默认值。在NotificationCombat中,您可以将振动、闪光和声音设置为用户的默认设置,如下所示:

.setDefaults(-1)

"-1"对应DEFAULT_ALL:http://developer.android.com/reference/android/app/Notification.html#DEFAULT_ALL

请注意,您必须要请求VIBRATE权限,否则会出错。请将以下内容添加到您的Android清单文件中:

<uses-permission android:name="android.permission.VIBRATE" />

5

我知道这个问题早就有人回答了,但我想提供我的解决方法,这种方法适用于多种组合的灯光、振动和声音,如果你要给用户提供启用或禁用它们的选项,那么这个方法非常有用。

int defaults = 0;
if (lights) {
    defaults = defaults | Notification.DEFAULT_LIGHTS;
}               
if (sound) {
    defaults = defaults | Notification.DEFAULT_SOUND;
}
if (vibrate) {
    defaults = defaults | Notification.DEFAULT_VIBRATE;
}
builder.setDefaults(defaults);

1

在果冻豆设备上,仅当通知优先级设置为最大或默认时,LED 才会工作,请再次检查。以下代码片段在我的 JB 设备上运行良好。

notification.setLights(0xFF0000FF,100,3000);
notification.setPriority(Notification.PRIORITY_DEFAULT);

这里我展示了蓝色 LED 用于通知,它将保持亮100毫秒,然后熄灭3000毫秒,直到用户解锁设备。

如果您正在使用 NotificationCompat(兼容性)类,请忽略 setDefaults 方法并使用 SetLight、SetSound、Setvibration 等方法。


2
对于那些使用兼容库的人来说,NotificationCompat.PRIORITY_DEFAULT是一个不错的选择! - Elad Nava
我正在使用Xperia Z1S的棒棒糖系统,通知指示灯无法工作。 - blackHawk
这个值0xFF0000FF是什么意思? - blackHawk

0

我遇到了同样的问题,但在这里找到了更好的解决方案。 这是一个 Kotlin 的解决方案:

fun getDefaults(val isSoundOn: Boolean, val isVibrate: Boolean, val isLightOn: Boolean): Int {
    var defaults = 0
    if (isLightOn && isSoundOn && isVibrate)
        return Notification.DEFAULT_ALL
    if (isLightOn) {
        defaults = defaults or Notification.DEFAULT_LIGHTS
    }
    if (isSoundOn) {
        defaults = defaults or Notification.DEFAULT_SOUND
    }
    if (isVibrate) {
        defaults = defaults or Notification.DEFAULT_VIBRATE
    }
    return defaults
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接