禁用通知的振动 [英] Disable vibration for a notification
问题描述
我正在使用通知编写应用程序.Google 开发者指南鼓励开发者提供自定义通知的设置(禁用振动、设置通知声音...),因此如果用户这样设置,我会尝试禁用通知的振动.
I'm writing an app using notification. Google developer guidelines encourages developers to provide settings to customize the notifications (disable vibration, set notification sound...), so I am trying to disable vibration for notifications if the user set it that way.
我正在使用 NotificationCompat.Builder
来创建通知,如下所示:
I am using NotificationCompat.Builder
to create the notification, like this:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Application.getContext())
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(largeIconBitmap)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.setContentTitle(title)
.setContentText(content);
我尝试了不同的方法来禁用通知:
I tried different ways to disable notifications:
notificationBuilder.setVibrate(null);
notificationBuilder.setVibrate(new long[]{0l, 0l});
notificationBuilder.setDefaults(Notification.DEFAULT_ALL | ~Notification.DEFAULT_VIBRATE);
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND);`
我还尝试在结果对象上构建通知和更改值:
I also tried to build the notification and change values on the resulting object:
Notification notification = notificationBuilder.build();
notification.vibrate = null;
但是出现通知时手机还是会震动.
But the phone still vibrates when the notification appears.
如何禁用通知的振动?
推荐答案
经过长时间的试用 &错误会话,我想我终于明白出了什么问题.
After a long trial & error session, I think I finally understood what's wrong.
问题出在这个指令notificationBuilder.setDefaults(Notification.DEFAULT_ALL)
.
无论您在设置 DEFAULT_ALL
或 DEFAULT_VIBRATE
后传递给 notificationBuilder.setVibrate()
什么参数,都将被静默丢弃.谷歌的某个人一定决定给予 setDefaults
比 setVibrate
更高的优先级.
No matter what parameter you pass to notificationBuilder.setVibrate()
after setting DEFAULT_ALL
or DEFAULT_VIBRATE
will be silently discarded. Someone at Google must have decided to give a higher precedence to setDefaults
than to setVibrate
.
这就是我最终在我的应用中禁用通知振动的方式:
This is how I ended up disabling vibration for notifications in my app:
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHT | Notification.DEFAULT_SOUND)
.setVibrate(new long[]{0L}); // Passing null here silently fails
这是可行的,但是为了禁用振动而初始化一个新的 long[]
感觉不对.
This works but doesn't feel right to initialize a new long[]
just to disable the vibration.
这篇关于禁用通知的振动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!