安卓 Oreo 上的通知 - 动态启用声音/振动

4
我有一个前台服务,显示一个进度通知,如果完成了,该通知将被重用作为普通通知来显示服务的结果。
我允许用户在我的应用程序内定义最终通知是否静音。这是我所做的:
// 1) Create notifcation channel in my app, once only
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(false);
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);

// 2) Init notification
notificationBuilder = new NotificationCompat.Builder(this, notificationChannelId);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setOngoing(true);
notificationBuilder.setTicker(ticker);
notificationBuilder.setContentText(title);

// 3) Updating the notification to show the services progress
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(subTitle);

// 4) preparing the final notification
if (!MainApp.getPrefs().silentNotifications()) {
    if (globalError || updated > 0 || prepared > 0 || contactsWithError.size() > 0) {
        notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
        notificationBuilder.setVibrate(new long[]{0, 500});
        notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    } else {
        notificationBuilder.setVibrate(new long[]{});
        notificationBuilder.setSound(null);
    }
}

问题

  • 一位安卓Oreo 用户告诉我,每次更新时通知会发出声音/震动
  • 同一用户告诉我,重新启动后,声音/震动就消失了

我的要求

  • 如果用户没有在我的频道中更改设置,我希望默认情况下通知频道能够震动并播放声音
  • 我想动态决定是否播放声音/振动,即使已启用声音/振动
  • 如果用户禁用我的频道的声音/振动,那么没关系,我将不会在任何时候播放声音或振动

我应该如何实现这个要求?

编辑-一个解决方案如下:

使用两个频道:

  • 一个用于更新通知
  • 一个用于最终结果通知

对我来说,这看起来很奇怪,我本以为可以使用一个频道,默认情况下设置其带有声音,并使用该频道。如果用户允许我播放声音,我应该能够自定义是否播放声音(目前似乎被强制播放声音)。否则,当然我永远不会播放声音。目前似乎需要为每个服务都使用两个频道,一个用于在通知中显示进度并在完成后默认播放声音,这很难向用户解释,因为您需要两个频道来执行相同的操作,一个用于进度,一个用于最终结果...


1
在Android 8.0+上使用两个不同的通知渠道(具有不同的声音/振动设置),其中您的“允许用户在我的应用程序内定义最终通知是否为静音”的逻辑驱动使用哪个通道。 - CommonsWare
1
这样,我必须告诉用户两个通道之间的区别。我想,如果用户允许我播放声音,我也应该能够不播放声音,如果这是可能的话,一个通道就足够了...但我可以按照您的建议去做。 - prom85
1个回答

0

我对我的通知声感到烦恼。我做了这个。

.setSound(Uri.parse("android.resources://" + getPackageName() + "/" + R.raw.silence))

和这个

.setOnlyAlertOnce(true)

请注意,您还必须在通道中设置它们。

嗨。如果我理解正确的话,除非将“静音片段”设置为声音,否则任何通知渠道都会默认有声音。那么,“R.raw.silence”是从哪里来的呢? :) - dentex
1
嗨,这只是一个放置在项目的raw文件夹中的静音文件。就像有自己的通知声音一样,在这里https://github.com/anars/blank-audio。我认为现在有更好的方法来定义静音通知,请再次阅读Android文档。 - Pedro Varela

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接