禁用通知的振动

新手上路,请多包涵

我正在使用通知编写一个应用程序。 Google 开发人员指南鼓励开发人员提供自定义通知的设置(禁用振动、设置通知声音…),因此如果用户以这种方式设置,我将尝试禁用通知的振动。

我正在使用 NotificationCompat.Builder 创建通知,如下所示:

 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);

我尝试了不同的方法来禁用通知:

 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);`

我还尝试在生成的对象上构建通知和更改值:

 Notification notification = notificationBuilder.build();
notification.vibrate = null;

但是当通知出现时手机仍然振动。

如何禁用通知振动?

原文由 nstCactus 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 675
2 个回答

经过长时间的试错,我想我终于明白出了什么问题。

问题在于这条指令 notificationBuilder.setDefaults(Notification.DEFAULT_ALL)

无论您在设置 DEFAULT_ALLDEFAULT_VIBRATE notificationBuilder.setVibrate() 什么参数--- 都将被静默丢弃。 Google 的某些人一定已经决定给予 setDefaultssetVibrate 更高的优先级。

这就是我最终在我的应用程序中禁用通知振动的方式:

 notificationBuilder.setDefaults(Notification.DEFAULT_LIGHT | Notification.DEFAULT_SOUND)
                   .setVibrate(new long[]{0L}); // Passing null here silently fails

这可行,但感觉不适合初始化一个新的 long[] 只是为了禁用振动。

原文由 nstCactus 发布,翻译遵循 CC BY-SA 3.0 许可协议

2020年:

将通知渠道的重要性设置为 NotificationManager.IMPORTANCE_NONE 对我有用。

原文由 Jakob 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题