我想为用户提供选择灯光,声音或振动或这三者的组合选项,以便在Notification
上发出警报。
在android文档中,我看到有一个DEFAULT_ALL
选项,其中将使用所有三种警报方法。
否则,可以选择其中任何一个(DEFAULT_LIGHTS
,DEFAULT_VIBRATE
,DEFAULT_SOUND
)。
有什么方法可以组合例如SOUND
和VIBRATION
但没有LIGHTS
和其他组合可以制作?
编辑
Notification.Builder's
(来自prolink007的回答)方法setDefaults(int default)
说:
该值应该是以下一个或多个字段与按位或:DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS结合使用。
该如何使用?
Notification.Builder API 11或NotificationCompat.Builder API 1提供了一些不同的方法来设置这些类型的警报。
该值应该是以下一个或多个字段与按位或:DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS结合使用。
未经测试,但我相信你会做这样的事情,如果你想要SOUND
,VIBRATION
和LIGHTS
:
setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE | DEFAULT_LIGHTS);
为了便携,我更喜欢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" />
我知道这个答案已经回答了一段时间,但只是想提供我的解决方案,它理想地适用于灯,振动和声音的多种组合,如果您为用户提供选项以启用或禁用它们。
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);
在jelly bean设备上,led仅在通知优先级设置为max或default时才有效,请再次检查。以下代码片段在jb设备上正常工作。
notification.setLights(0xFF0000FF,100,3000);
notification.setPriority(Notification.PRIORITY_DEFAULT);
在这里,我显示蓝色LED通知,它将保持100毫秒并关闭3000毫秒,直到用户解锁他的设备。
并检查您是否使用NotificationCompat(兼容性)类而不是忽略setDefaults方法并使用SetLight,SetSound,Setvibration等
我遇到了同样的问题,但登陆后得到了更好的解决方案。这是一个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
}