设置振动,灯光或声音的组合,以便在android中进行通知

时间:2012-08-17 13:25:50

标签: android android-notifications

我想为用户提供选择灯光,声音或振动或这三者的组合选项,以便在Notification上发出警报。

在Android文档中,我看到有一个DEFAULT_ALL选项,其中将使用所有三种警报方法。

否则,可以选择其中任何一个(DEFAULT_LIGHTSDEFAULT_VIBRATEDEFAULT_SOUND)。

有没有什么方法可以组合使用例如SOUNDVIBRATION但没有LIGHTS和其他组合?


修改

Notification.Builder's(来自prolink007的回答)方法setDefaults(int default)说:

  

该值应该是以下一个或多个字段与按位或结合使用:DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS。

应如何使用?

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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" />

答案 2 :(得分: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);

答案 3 :(得分:1)

在jelly bean设备上,led仅在通知优先级设置为max或default时有效,请再次检查。以下代码段在jb设备上正常工作。

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

在这里,我显示蓝色指示通知,该通知将保持100毫秒并关闭3000毫秒,直到用户解锁他的设备。

检查您是否使用NotificationCompat(兼容性)类而不是忽略setDefaults方法并使用SetLight,SetSound,Setvibration等

答案 4 :(得分: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
}