【问题标题】:How to send a notification with sound and vibration in do not disturb(DND) mode in android如何在android中的请勿打扰(DND)模式下发送带有声音和振动的通知
【发布时间】:2018-03-22 21:58:43
【问题描述】:

当手机在 Android 设备上处于请勿打扰模式时,如何发送带有声音和振动的通知。 我使用以下代码,当我的应用程序当前处于前台时它正在工作。

PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
            resultIntent, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText("You've received new message."))
            .setContentText("You've received new message.");

    // FOR SILENT MODE
    AudioManager am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
    // For Normal mode
    am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
    am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);

    mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

    // Set Vibrate, Sound and Light
    int defaults = 0;
    defaults = defaults | Notification.DEFAULT_LIGHTS;
    // defaults = defaults | Notification.DEFAULT_VIBRATE;
    // defaults = defaults | Notification.DEFAULT_SOUND;
    mBuilder.setDefaults(defaults);
    mBuilder.setSound(Uri.parse("android.resource://" + getPackageName()
    + "/" + R.raw.siren));

    // Cancel the notification after its selection
    mBuilder.setAutoCancel(true);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

当我的应用在后台时,我还想要带有声音和振动的通知。

【问题讨论】:

    标签: android android-notifications


    【解决方案1】:

    一般来说你不能。即使是MAX 优先级的通知也不会在免打扰模式下显示。

    我可以想象的可能的解决方法是使用android.permission.SYSTEM_ALERT_WINDOW 在系统窗口上绘制自定义通知(FB Messanger 的工作方式类似):Creating a system overlay window (always on top)。 但这种方法只适用于极少数情况,而且大多数情况下它违反了 Android UI/UX 最佳实践。

    【讨论】:

      【解决方案2】:

      好消息,你已经完成了一半。

      我之前通过使用 AudioManagerVIBRATOR_SERVICE 实现了这一点(是的,我知道;)

      我们的想法是不要使用 NotificationCompat.Builder,因为它依赖于系统设置,如果设备处于静音模式,它不会振动也不会播放声音。您必须使用 AudioManager 手动播放声音并使用 VIBRATOR_SERVICE 进行振动。

      您正在使用 AudioManager 并设置属性,但您从未真正要求它播放声音。因此,在您的代码中,它从未实际使用过。

      这里是an example如何使用AudioManager播放声音,它也会忽略静音模式:

      这是使用 VIBRATOR_SERVICEan example

      结合这两种方法并放弃 NotificationCompat.Builder

      【讨论】:

        【解决方案3】:

        如果您可以获得更改设备设置的正确权限,那么您可以在应用中显示带有声音和振动的通知。还要检查this out

        【讨论】:

          猜你喜欢
          • 2015-10-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-30
          • 1970-01-01
          • 1970-01-01
          • 2020-12-16
          • 1970-01-01
          相关资源
          最近更新 更多