From 179bc6266e0bb2116bb1fc794a01522da956534f Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Thu, 12 Nov 2026 15:19:19 +0100 Subject: [PATCH 1/7] fix(notifications): offer ringtones when choosing the call sound On some OEMs (e.g. Samsung) the system notification channel settings only offer notification sounds for the calls channel, even though it uses USAGE_NOTIFICATION_RINGTONE, so no call ringtone could be selected. Open an in-app ringtone picker with TYPE_RINGTONE instead (as done by Signal). As the sound of an existing channel can't be changed by the app, the calls channel is recreated under a new versioned id (NOTIFICATION_CHANNEL_CALLS_V5__) keeping its other settings. The system channel settings are still opened if the channel is disabled or no ringtone picker is available. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../nextcloud/talk/jobs/NotificationWorker.kt | 2 +- .../nextcloud/talk/utils/NotificationUtils.kt | 94 +++++++++++++++++-- 2 files changed, 85 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt b/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt index 6da846891d8..7f67e29e974 100644 --- a/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt +++ b/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt @@ -327,7 +327,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor ) val soundUri = getCallRingtoneUri(applicationContext, appPreferences) - val notificationChannelId = NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + val notificationChannelId = NotificationUtils.getCallsNotificationChannelId(applicationContext) val uri = user.baseUrl!!.toUri() val baseUrl = uri.host diff --git a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt index 62332359bed..14d0a35448d 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt @@ -66,6 +66,22 @@ object NotificationUtils { private const val BITMAP_COMPRESSION_QUALITY = 100 + /** + * The sound of a notification channel can't be changed by the app once the channel exists, and a deleted + * channel is restored with its old settings when it is recreated with the same id. So whenever the call + * ringtone is changed in-app, the calls channel is recreated with the base id plus this separator plus a + * timestamp, e.g. "NOTIFICATION_CHANNEL_CALLS_V5__1762950000000". + * + * This suffix is independent of the "_V5" in the base id: + * - "_V5" is a code-level version. It is bumped by developers when a release must reset the channel for all + * installations (e.g. changed audio attributes). Bumping it drops every channel with the old base id, + * including the timestamped ones, via [removeOldNotificationChannels]. + * - The timestamp suffix is a runtime version. It differs per installation and only changes when the user + * picks a new call ringtone. It is not a counter on top of "_V5" (V5 -> V6 -> ...), because such runtime + * bumps would collide with future code-level bumps. + */ + private const val CHANNEL_ID_VERSION_SEPARATOR = "__" + private fun createNotificationChannel( context: Context, notificationChannel: Channel, @@ -99,27 +115,85 @@ object NotificationUtils { } } + private fun callsAudioAttributes(): AudioAttributes = + AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) + .build() + private fun createCallsNotificationChannel(context: Context, appPreferences: AppPreferences) { - val audioAttributes = - AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) - .build() val soundUri = getCallRingtoneUri(context, appPreferences) createNotificationChannel( context, Channel( - NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name, + getCallsNotificationChannelId(context), context.resources.getString(R.string.nc_notification_channel_calls), context.resources.getString(R.string.nc_notification_channel_calls_description), true ), soundUri, - audioAttributes + callsAudioAttributes() ) } + private fun isCallsNotificationChannelId(channelId: String): Boolean { + val baseId = NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + return channelId == baseId || channelId.startsWith(baseId + CHANNEL_ID_VERSION_SEPARATOR) + } + + /** + * Returns the id of the current incoming calls channel. It is versioned because it is recreated whenever the + * call ringtone is changed, see [updateCallRingtone]. + */ + fun getCallsNotificationChannelId(context: Context): String { + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + return notificationManager.notificationChannels + .firstOrNull { isCallsNotificationChannelId(it.id) } + ?.id + ?: NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + } + + /** + * Sets a new call ringtone (null = silent). The sound of an existing channel can't be changed by the app, so + * the calls channel is recreated under a new id, keeping all other settings of the existing channel. + * + * This is needed because the system channel settings of some OEMs (e.g. Samsung) only offer notification + * sounds, even for channels with [AudioAttributes.USAGE_NOTIFICATION_RINGTONE]. + */ + fun updateCallRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?) { + appPreferences.callRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) + + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val existingChannel = notificationManager.getNotificationChannel(getCallsNotificationChannelId(context)) + if (existingChannel == null) { + createCallsNotificationChannel(context, appPreferences) + return + } + if (existingChannel.sound == ringtoneUri) { + return + } + + val newChannelId = NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + + CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() + val newChannel = NotificationChannel(newChannelId, existingChannel.name, existingChannel.importance).apply { + description = existingChannel.description + group = existingChannel.group + setSound(ringtoneUri, existingChannel.audioAttributes ?: callsAudioAttributes()) + enableLights(existingChannel.shouldShowLights()) + lightColor = existingChannel.lightColor + enableVibration(existingChannel.shouldVibrate()) + vibrationPattern = existingChannel.vibrationPattern + lockscreenVisibility = existingChannel.lockscreenVisibility + setShowBadge(existingChannel.canShowBadge()) + setBypassDnd(existingChannel.canBypassDnd()) + } + + Log.i(TAG, "Recreating calls channel ${existingChannel.id} as $newChannelId with new ringtone") + notificationManager.deleteNotificationChannel(existingChannel.id) + notificationManager.createNotificationChannel(newChannel) + } + /** * Separate from [NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5] (the incoming-ring channel, * which must stay IMPORTANCE_HIGH) so the persistent "call in progress" foreground-service @@ -193,7 +267,7 @@ object NotificationUtils { // Delete all notification channels created by previous versions for (channel in notificationManager.notificationChannels) { - if (!channelsToKeep.contains(channel.id)) { + if (!channelsToKeep.contains(channel.id) && !isCallsNotificationChannelId(channel.id)) { notificationManager.deleteNotificationChannel(channel.id) } } @@ -286,7 +360,7 @@ object NotificationUtils { } fun isCallsNotificationChannelEnabled(context: Context): Boolean { - val channel = getNotificationChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name) + val channel = getNotificationChannel(context, getCallsNotificationChannelId(context)) if (channel != null) { return isNotificationChannelEnabled(channel) } @@ -340,7 +414,7 @@ object NotificationUtils { context, appPreferences.callRingtoneUri, DEFAULT_CALL_RINGTONE_URI, - NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + getCallsNotificationChannelId(context) ) fun getMessageRingtoneUri(context: Context, appPreferences: AppPreferences): Uri? = From f339f745db7e1cc5f552912b4448dee91bcd4cf9 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Thu, 12 Nov 2026 15:43:16 +0100 Subject: [PATCH 2/7] fix(notifications): allow returning to the bundled default sounds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The app ships its own default sounds ("Librem by feandesign") for calls and messages. These are app resources, not system sounds, so neither the system channel settings nor the system ringtone picker offer them. Once a user picked another call ringtone or message sound, there was no way back to the bundled default. Tapping the call or message sound now shows a dialog offering the bundled default or "Other sound…", which opens the system picker. The picker's "Default" entry now refers to the phone's default ringtone/notification sound, so it means the same on all devices. Message sounds are chosen in-app like call ringtones. As the sound of an existing channel can't be changed by the app, the messages channel is recreated under a versioned id (NOTIFICATION_CHANNEL_MESSAGES_V4__) the same way as the calls channel, sharing the recreation logic. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../nextcloud/talk/jobs/NotificationWorker.kt | 5 +- .../nextcloud/talk/utils/NotificationUtils.kt | 145 ++++++++++++------ app/src/main/res/values/strings.xml | 1 + 3 files changed, 97 insertions(+), 54 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt b/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt index 7f67e29e974..26e8e474a72 100644 --- a/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt +++ b/app/src/main/java/com/nextcloud/talk/jobs/NotificationWorker.kt @@ -771,7 +771,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor TYPE_ADMIN_NOTIFICATIONS, TYPE_REMOTE_TALK_SHARE -> { notificationBuilder.setChannelId( - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name + NotificationUtils.getMessagesNotificationChannelId(applicationContext) ) } } @@ -1231,8 +1231,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor if (isOngoingCallNotificationVisible) { val notificationBuilder = NotificationCompat.Builder( context!!, - NotificationUtils.NotificationChannels - .NOTIFICATION_CHANNEL_MESSAGES_V4.name + NotificationUtils.getMessagesNotificationChannelId(context!!) ) val intent = createContentIntent() diff --git a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt index 14d0a35448d..ecb23d21922 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt @@ -69,15 +69,15 @@ object NotificationUtils { /** * The sound of a notification channel can't be changed by the app once the channel exists, and a deleted * channel is restored with its old settings when it is recreated with the same id. So whenever the call - * ringtone is changed in-app, the calls channel is recreated with the base id plus this separator plus a - * timestamp, e.g. "NOTIFICATION_CHANNEL_CALLS_V5__1762950000000". + * ringtone or message sound is changed in-app, the channel is recreated with the base id plus this separator + * plus a timestamp, e.g. "NOTIFICATION_CHANNEL_CALLS_V5__1762950000000". * * This suffix is independent of the "_V5" in the base id: * - "_V5" is a code-level version. It is bumped by developers when a release must reset the channel for all * installations (e.g. changed audio attributes). Bumping it drops every channel with the old base id, * including the timestamped ones, via [removeOldNotificationChannels]. * - The timestamp suffix is a runtime version. It differs per installation and only changes when the user - * picks a new call ringtone. It is not a counter on top of "_V5" (V5 -> V6 -> ...), because such runtime + * picks a new sound. It is not a counter on top of "_V5" (V5 -> V6 -> ...), because such runtime * bumps would collide with future code-level bumps. */ private const val CHANNEL_ID_VERSION_SEPARATOR = "__" @@ -137,61 +137,103 @@ object NotificationUtils { ) } - private fun isCallsNotificationChannelId(channelId: String): Boolean { - val baseId = NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name - return channelId == baseId || channelId.startsWith(baseId + CHANNEL_ID_VERSION_SEPARATOR) + private fun isVersionedChannelId(channelId: String, baseId: String): Boolean = + channelId == baseId || channelId.startsWith(baseId + CHANNEL_ID_VERSION_SEPARATOR) + + private fun getVersionedChannelId(context: Context, baseId: String): String { + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + return notificationManager.notificationChannels + .firstOrNull { isVersionedChannelId(it.id, baseId) } + ?.id + ?: baseId } /** * Returns the id of the current incoming calls channel. It is versioned because it is recreated whenever the * call ringtone is changed, see [updateCallRingtone]. */ - fun getCallsNotificationChannelId(context: Context): String { - val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - return notificationManager.notificationChannels - .firstOrNull { isCallsNotificationChannelId(it.id) } - ?.id - ?: NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name - } + fun getCallsNotificationChannelId(context: Context): String = + getVersionedChannelId(context, NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name) /** - * Sets a new call ringtone (null = silent). The sound of an existing channel can't be changed by the app, so - * the calls channel is recreated under a new id, keeping all other settings of the existing channel. + * Returns the id of the current messages channel. It is versioned because it is recreated whenever the + * message sound is changed, see [updateMessageRingtone]. + */ + fun getMessagesNotificationChannelId(context: Context): String = + getVersionedChannelId(context, NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name) + + /** + * Sets a new call ringtone (null = silent). * - * This is needed because the system channel settings of some OEMs (e.g. Samsung) only offer notification - * sounds, even for channels with [AudioAttributes.USAGE_NOTIFICATION_RINGTONE]. + * The ringtone is chosen in-app because the system channel settings of some OEMs (e.g. Samsung) only offer + * notification sounds, even for channels with [AudioAttributes.USAGE_NOTIFICATION_RINGTONE], and never offer + * the bundled default sound. */ fun updateCallRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?) { appPreferences.callRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) - - val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - val existingChannel = notificationManager.getNotificationChannel(getCallsNotificationChannelId(context)) - if (existingChannel == null) { + val recreated = recreateChannelWithSound( + context, + NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name, + ringtoneUri, + callsAudioAttributes() + ) + if (!recreated) { createCallsNotificationChannel(context, appPreferences) - return - } - if (existingChannel.sound == ringtoneUri) { - return } + } - val newChannelId = NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + - CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() - val newChannel = NotificationChannel(newChannelId, existingChannel.name, existingChannel.importance).apply { - description = existingChannel.description - group = existingChannel.group - setSound(ringtoneUri, existingChannel.audioAttributes ?: callsAudioAttributes()) - enableLights(existingChannel.shouldShowLights()) - lightColor = existingChannel.lightColor - enableVibration(existingChannel.shouldVibrate()) - vibrationPattern = existingChannel.vibrationPattern - lockscreenVisibility = existingChannel.lockscreenVisibility - setShowBadge(existingChannel.canShowBadge()) - setBypassDnd(existingChannel.canBypassDnd()) + /** + * Sets a new message sound (null = silent). It is chosen in-app because the system channel settings never + * offer the bundled default sound. + */ + fun updateMessageRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?) { + appPreferences.messageRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) + val recreated = recreateChannelWithSound( + context, + NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name, + ringtoneUri, + messagesAudioAttributes() + ) + if (!recreated) { + createMessagesNotificationChannel(context, appPreferences) } + } - Log.i(TAG, "Recreating calls channel ${existingChannel.id} as $newChannelId with new ringtone") - notificationManager.deleteNotificationChannel(existingChannel.id) - notificationManager.createNotificationChannel(newChannel) + /** + * The sound of an existing channel can't be changed by the app, so the channel is recreated under a new id, + * keeping all other settings of the existing channel. + * + * @return false if there is no existing channel to recreate + */ + private fun recreateChannelWithSound( + context: Context, + baseId: String, + sound: Uri?, + fallbackAudioAttributes: AudioAttributes + ): Boolean { + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val existingChannel = notificationManager.getNotificationChannel(getVersionedChannelId(context, baseId)) + ?: return false + if (existingChannel.sound != sound) { + val newChannelId = baseId + CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() + val newChannel = NotificationChannel(newChannelId, existingChannel.name, existingChannel.importance).apply { + description = existingChannel.description + group = existingChannel.group + setSound(sound, existingChannel.audioAttributes ?: fallbackAudioAttributes) + enableLights(existingChannel.shouldShowLights()) + lightColor = existingChannel.lightColor + enableVibration(existingChannel.shouldVibrate()) + vibrationPattern = existingChannel.vibrationPattern + lockscreenVisibility = existingChannel.lockscreenVisibility + setShowBadge(existingChannel.canShowBadge()) + setBypassDnd(existingChannel.canBypassDnd()) + } + + Log.i(TAG, "Recreating channel ${existingChannel.id} as $newChannelId with new sound") + notificationManager.deleteNotificationChannel(existingChannel.id) + notificationManager.createNotificationChannel(newChannel) + } + return true } /** @@ -213,24 +255,25 @@ object NotificationUtils { ) } + private fun messagesAudioAttributes(): AudioAttributes = + AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) + .build() + private fun createMessagesNotificationChannel(context: Context, appPreferences: AppPreferences) { - val audioAttributes = - AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) - .build() val soundUri = getMessageRingtoneUri(context, appPreferences) createNotificationChannel( context, Channel( - NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name, + getMessagesNotificationChannelId(context), context.resources.getString(R.string.nc_notification_channel_messages), context.resources.getString(R.string.nc_notification_channel_messages_description), true ), soundUri, - audioAttributes + messagesAudioAttributes() ) } @@ -267,7 +310,7 @@ object NotificationUtils { // Delete all notification channels created by previous versions for (channel in notificationManager.notificationChannels) { - if (!channelsToKeep.contains(channel.id) && !isCallsNotificationChannelId(channel.id)) { + if (channelsToKeep.none { isVersionedChannelId(channel.id, it) }) { notificationManager.deleteNotificationChannel(channel.id) } } @@ -368,7 +411,7 @@ object NotificationUtils { } fun isMessagesNotificationChannelEnabled(context: Context): Boolean { - val channel = getNotificationChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name) + val channel = getNotificationChannel(context, getMessagesNotificationChannelId(context)) if (channel != null) { return isNotificationChannelEnabled(channel) } @@ -422,7 +465,7 @@ object NotificationUtils { context, appPreferences.messageRingtoneUri, DEFAULT_MESSAGE_RINGTONE_URI, - NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name + getMessagesNotificationChannelId(context) ) fun loadAvatarSync(avatarUrl: String, context: Context, credentials: String? = null): IconCompat? { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b8aa0a54909..5cfe6ce51e1 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -129,6 +129,7 @@ How to translate with transifex: Messages Librem by feandesign No sound + Other sound… Server notifications app not installed Please contact the administrator of Battery settings From dde7d8fd62b0bf164ebf4b7d4ba9aef31eb029d0 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Fri, 13 Nov 2026 10:56:37 +0100 Subject: [PATCH 3/7] refactor(notifications): recreate sound channels without copying settings Copying the old channel's settings into the recreated channel was not reliable: the vibration pattern overwrote the copied vibration flag, and settings like bypassing Do Not Disturb or lock screen visibility are reset by the system when an app creates a channel anyway. As changing the sound is rare, the channel is now simply recreated with the app defaults and the new sound, reusing the existing channel creation code. The new channel is created before the old one is deleted, so there is no moment without a channel, and the newest versioned channel is used if more than one exists. Also avoid crashes when a ringtone can't be resolved for its title, and when the system channel settings can't be opened. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../nextcloud/talk/utils/NotificationUtils.kt | 157 +++++++----------- 1 file changed, 56 insertions(+), 101 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt index ecb23d21922..396c88ebc86 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt @@ -67,18 +67,8 @@ object NotificationUtils { private const val BITMAP_COMPRESSION_QUALITY = 100 /** - * The sound of a notification channel can't be changed by the app once the channel exists, and a deleted - * channel is restored with its old settings when it is recreated with the same id. So whenever the call - * ringtone or message sound is changed in-app, the channel is recreated with the base id plus this separator - * plus a timestamp, e.g. "NOTIFICATION_CHANNEL_CALLS_V5__1762950000000". - * - * This suffix is independent of the "_V5" in the base id: - * - "_V5" is a code-level version. It is bumped by developers when a release must reset the channel for all - * installations (e.g. changed audio attributes). Bumping it drops every channel with the old base id, - * including the timestamped ones, via [removeOldNotificationChannels]. - * - The timestamp suffix is a runtime version. It differs per installation and only changes when the user - * picks a new sound. It is not a counter on top of "_V5" (V5 -> V6 -> ...), because such runtime - * bumps would collide with future code-level bumps. + * Separates a channel base id from a timestamp, e.g. "NOTIFICATION_CHANNEL_CALLS_V5__1762950000000". The app + * can't change the sound of an existing channel, so the channel is replaced under a new id, see [replaceChannel]. */ private const val CHANNEL_ID_VERSION_SEPARATOR = "__" @@ -115,125 +105,84 @@ object NotificationUtils { } } - private fun callsAudioAttributes(): AudioAttributes = - AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) - .build() - - private fun createCallsNotificationChannel(context: Context, appPreferences: AppPreferences) { - val soundUri = getCallRingtoneUri(context, appPreferences) + private fun createCallsNotificationChannel(context: Context, channelId: String, soundUri: Uri?) { + val audioAttributes = + AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) + .build() createNotificationChannel( context, Channel( - getCallsNotificationChannelId(context), + channelId, context.resources.getString(R.string.nc_notification_channel_calls), context.resources.getString(R.string.nc_notification_channel_calls_description), true ), soundUri, - callsAudioAttributes() + audioAttributes ) } - private fun isVersionedChannelId(channelId: String, baseId: String): Boolean = - channelId == baseId || channelId.startsWith(baseId + CHANNEL_ID_VERSION_SEPARATOR) + private fun channelVersion(channelId: String, baseId: String): Long? = + when { + channelId == baseId -> 0L + channelId.startsWith(baseId + CHANNEL_ID_VERSION_SEPARATOR) -> + channelId.removePrefix(baseId + CHANNEL_ID_VERSION_SEPARATOR).toLongOrNull() + else -> null + } private fun getVersionedChannelId(context: Context, baseId: String): String { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager return notificationManager.notificationChannels - .firstOrNull { isVersionedChannelId(it.id, baseId) } - ?.id + .mapNotNull { channel -> channelVersion(channel.id, baseId)?.let { version -> version to channel.id } } + .maxByOrNull { it.first } + ?.second ?: baseId } - /** - * Returns the id of the current incoming calls channel. It is versioned because it is recreated whenever the - * call ringtone is changed, see [updateCallRingtone]. - */ fun getCallsNotificationChannelId(context: Context): String = getVersionedChannelId(context, NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name) - /** - * Returns the id of the current messages channel. It is versioned because it is recreated whenever the - * message sound is changed, see [updateMessageRingtone]. - */ fun getMessagesNotificationChannelId(context: Context): String = getVersionedChannelId(context, NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name) /** - * Sets a new call ringtone (null = silent). - * - * The ringtone is chosen in-app because the system channel settings of some OEMs (e.g. Samsung) only offer - * notification sounds, even for channels with [AudioAttributes.USAGE_NOTIFICATION_RINGTONE], and never offer - * the bundled default sound. + * @param ringtoneUri null for silent */ fun updateCallRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?) { appPreferences.callRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) - val recreated = recreateChannelWithSound( - context, - NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name, - ringtoneUri, - callsAudioAttributes() - ) - if (!recreated) { - createCallsNotificationChannel(context, appPreferences) + replaceChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name, ringtoneUri) { channelId -> + createCallsNotificationChannel(context, channelId, ringtoneUri) } } /** - * Sets a new message sound (null = silent). It is chosen in-app because the system channel settings never - * offer the bundled default sound. + * @param ringtoneUri null for silent */ fun updateMessageRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?) { appPreferences.messageRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) - val recreated = recreateChannelWithSound( - context, - NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name, - ringtoneUri, - messagesAudioAttributes() - ) - if (!recreated) { - createMessagesNotificationChannel(context, appPreferences) + replaceChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name, ringtoneUri) { channelId -> + createMessagesNotificationChannel(context, channelId, ringtoneUri) } } /** - * The sound of an existing channel can't be changed by the app, so the channel is recreated under a new id, - * keeping all other settings of the existing channel. - * - * @return false if there is no existing channel to recreate + * Creates a new channel with a new id and then deletes the old ones. Other settings the user changed in the + * system settings for the old channel are not kept. */ - private fun recreateChannelWithSound( - context: Context, - baseId: String, - sound: Uri?, - fallbackAudioAttributes: AudioAttributes - ): Boolean { + private fun replaceChannel(context: Context, baseId: String, sound: Uri?, createChannel: (String) -> Unit) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - val existingChannel = notificationManager.getNotificationChannel(getVersionedChannelId(context, baseId)) - ?: return false - if (existingChannel.sound != sound) { - val newChannelId = baseId + CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() - val newChannel = NotificationChannel(newChannelId, existingChannel.name, existingChannel.importance).apply { - description = existingChannel.description - group = existingChannel.group - setSound(sound, existingChannel.audioAttributes ?: fallbackAudioAttributes) - enableLights(existingChannel.shouldShowLights()) - lightColor = existingChannel.lightColor - enableVibration(existingChannel.shouldVibrate()) - vibrationPattern = existingChannel.vibrationPattern - lockscreenVisibility = existingChannel.lockscreenVisibility - setShowBadge(existingChannel.canShowBadge()) - setBypassDnd(existingChannel.canBypassDnd()) - } - - Log.i(TAG, "Recreating channel ${existingChannel.id} as $newChannelId with new sound") - notificationManager.deleteNotificationChannel(existingChannel.id) - notificationManager.createNotificationChannel(newChannel) + val oldChannels = notificationManager.notificationChannels.filter { channelVersion(it.id, baseId) != null } + if (oldChannels.size == 1 && oldChannels.first().sound == sound) { + return } - return true + + val newChannelId = baseId + CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() + createChannel(newChannelId) + oldChannels.forEach { notificationManager.deleteNotificationChannel(it.id) } + Log.i(TAG, "Replaced channels ${oldChannels.map { it.id }} with $newChannelId") } /** @@ -255,25 +204,23 @@ object NotificationUtils { ) } - private fun messagesAudioAttributes(): AudioAttributes = - AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) - .build() - - private fun createMessagesNotificationChannel(context: Context, appPreferences: AppPreferences) { - val soundUri = getMessageRingtoneUri(context, appPreferences) + private fun createMessagesNotificationChannel(context: Context, channelId: String, soundUri: Uri?) { + val audioAttributes = + AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) + .build() createNotificationChannel( context, Channel( - getMessagesNotificationChannelId(context), + channelId, context.resources.getString(R.string.nc_notification_channel_messages), context.resources.getString(R.string.nc_notification_channel_messages_description), true ), soundUri, - messagesAudioAttributes() + audioAttributes ) } @@ -292,9 +239,17 @@ object NotificationUtils { } fun registerNotificationChannels(context: Context, appPreferences: AppPreferences) { - createCallsNotificationChannel(context, appPreferences) + createCallsNotificationChannel( + context, + getCallsNotificationChannelId(context), + getCallRingtoneUri(context, appPreferences) + ) createOngoingCallNotificationChannel(context) - createMessagesNotificationChannel(context, appPreferences) + createMessagesNotificationChannel( + context, + getMessagesNotificationChannelId(context), + getMessageRingtoneUri(context, appPreferences) + ) createUploadsNotificationChannel(context) } @@ -310,7 +265,7 @@ object NotificationUtils { // Delete all notification channels created by previous versions for (channel in notificationManager.notificationChannels) { - if (channelsToKeep.none { isVersionedChannelId(channel.id, it) }) { + if (channelsToKeep.none { channelVersion(channel.id, it) != null }) { notificationManager.deleteNotificationChannel(channel.id) } } From 10708769511a5702d2b266593d02075d92a048d2 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Fri, 13 Nov 2026 10:59:36 +0100 Subject: [PATCH 4/7] fix(notifications): handle invalid sound picker results Some ringtone pickers return RESULT_OK without EXTRA_RINGTONE_PICKED_URI. This was read as "silent" and muted calls or messages although the user never chose silent. Such results are now ignored like a cancel. The system may reject a channel sound the app is not allowed to read with a SecurityException, which crashed the settings screen. Now the old channel is kept, the preference is not changed and an error toast is shown. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../nextcloud/talk/utils/NotificationUtils.kt | 47 ++++++++++++++----- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt index 396c88ebc86..10cbd0875d2 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt @@ -150,39 +150,64 @@ object NotificationUtils { /** * @param ringtoneUri null for silent + * @return false if the ringtone could not be set */ - fun updateCallRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?) { - appPreferences.callRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) - replaceChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name, ringtoneUri) { channelId -> + fun updateCallRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?): Boolean { + val baseId = NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name + val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId -> createCallsNotificationChannel(context, channelId, ringtoneUri) } + if (replaced) { + appPreferences.callRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) + } + return replaced } /** * @param ringtoneUri null for silent + * @return false if the sound could not be set */ - fun updateMessageRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?) { - appPreferences.messageRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) - replaceChannel(context, NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name, ringtoneUri) { channelId -> + fun updateMessageRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?): Boolean { + val baseId = NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name + val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId -> createMessagesNotificationChannel(context, channelId, ringtoneUri) } + if (replaced) { + appPreferences.messageRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) + } + return replaced } /** * Creates a new channel with a new id and then deletes the old ones. Other settings the user changed in the * system settings for the old channel are not kept. */ - private fun replaceChannel(context: Context, baseId: String, sound: Uri?, createChannel: (String) -> Unit) { + private fun replaceChannel( + context: Context, + baseId: String, + sound: Uri?, + createChannel: (String) -> Unit + ): Boolean { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val oldChannels = notificationManager.notificationChannels.filter { channelVersion(it.id, baseId) != null } if (oldChannels.size == 1 && oldChannels.first().sound == sound) { - return + return true } val newChannelId = baseId + CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() - createChannel(newChannelId) - oldChannels.forEach { notificationManager.deleteNotificationChannel(it.id) } - Log.i(TAG, "Replaced channels ${oldChannels.map { it.id }} with $newChannelId") + val created = try { + createChannel(newChannelId) + true + } catch (e: SecurityException) { + // the system rejects sounds the app is not allowed to read + Log.e(TAG, "Failed to create channel $newChannelId with sound $sound", e) + false + } + if (created) { + oldChannels.forEach { notificationManager.deleteNotificationChannel(it.id) } + Log.i(TAG, "Replaced channels ${oldChannels.map { it.id }} with $newChannelId") + } + return created } /** From 655d84b18ac06f7dba8de7cd35347dd02c4a6a85 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Mon, 16 Nov 2026 21:25:35 +0100 Subject: [PATCH 5/7] fix(notifications): harden sound change handling and remove duplication - Catch all runtime exceptions when creating the replacement channel. Some OEMs throw IllegalArgumentException for invalid sounds, and file:// uris from third-party pickers can throw as well, which crashed the settings screen. The old channel is kept and an error toast is shown. - Use one update function per sound for both the picker result and the sound dialog, so both paths can't diverge. - Take the preview's audio usage from NotificationUtils, so the preview plays on the same volume stream as the real notification. - Only refresh the sound labels after a change, instead of re-running the whole setup, which re-registered click listeners and could re-trigger the notification warning blink animation. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../com/nextcloud/talk/utils/NotificationUtils.kt | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt index 10cbd0875d2..a72c3dbedf5 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt @@ -72,6 +72,9 @@ object NotificationUtils { */ private const val CHANNEL_ID_VERSION_SEPARATOR = "__" + const val CALLS_AUDIO_USAGE = AudioAttributes.USAGE_NOTIFICATION_RINGTONE + const val MESSAGES_AUDIO_USAGE = AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT + private fun createNotificationChannel( context: Context, notificationChannel: Channel, @@ -109,7 +112,7 @@ object NotificationUtils { val audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) + .setUsage(CALLS_AUDIO_USAGE) .build() createNotificationChannel( @@ -182,6 +185,7 @@ object NotificationUtils { * Creates a new channel with a new id and then deletes the old ones. Other settings the user changed in the * system settings for the old channel are not kept. */ + @Suppress("TooGenericExceptionCaught") private fun replaceChannel( context: Context, baseId: String, @@ -198,8 +202,8 @@ object NotificationUtils { val created = try { createChannel(newChannelId) true - } catch (e: SecurityException) { - // the system rejects sounds the app is not allowed to read + } catch (e: RuntimeException) { + // e.g. SecurityException for sounds the app is not allowed to read, or invalid sound uris Log.e(TAG, "Failed to create channel $newChannelId with sound $sound", e) false } @@ -233,7 +237,7 @@ object NotificationUtils { val audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT) + .setUsage(MESSAGES_AUDIO_USAGE) .build() createNotificationChannel( From b8cb11a51763caeaf80aff87942c16f5ef952011 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Tue, 17 Nov 2026 10:55:23 +0100 Subject: [PATCH 6/7] fix(notifications): keep channel settings when changing the sound Changing the call or message sound replaces the notification channel under a new id, because Android doesn't let an app change the sound of an existing channel. Until now the new channel started with the app defaults, so any settings the user had changed in the system settings (importance, vibration, lights, badge, lock screen visibility) were lost with every sound change. The settings of the current channel are now copied to the new one, as Signal does. The vibration flag is set after the vibration pattern, because setting the pattern also changes the flag. Some settings may still be ignored by the system for new channels, e.g. bypassing Do Not Disturb without policy access. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../nextcloud/talk/utils/NotificationUtils.kt | 57 ++++++++++++++----- 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt index a72c3dbedf5..2ef17ab79e3 100644 --- a/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt +++ b/app/src/main/java/com/nextcloud/talk/utils/NotificationUtils.kt @@ -79,7 +79,8 @@ object NotificationUtils { context: Context, notificationChannel: Channel, sound: Uri?, - audioAttributes: AudioAttributes? + audioAttributes: AudioAttributes?, + copySettingsFrom: NotificationChannel? = null ) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager @@ -103,12 +104,34 @@ object NotificationUtils { channel.lightColor = R.color.colorPrimary channel.setSound(sound, audioAttributes) channel.setBypassDnd(false) + copySettingsFrom?.let { copyUserSettings(it, channel) } notificationManager.createNotificationChannel(channel) } } - private fun createCallsNotificationChannel(context: Context, channelId: String, soundUri: Uri?) { + /** + * Keeps the settings the user may have changed for [from] in the system settings, except the sound. The system + * ignores some of them for new channels, e.g. bypassing Do Not Disturb without policy access. + */ + private fun copyUserSettings(from: NotificationChannel, to: NotificationChannel) { + to.importance = from.importance + to.enableLights(from.shouldShowLights()) + to.lightColor = from.lightColor + // setting the pattern also changes the vibration flag, so the flag is set afterwards + to.vibrationPattern = from.vibrationPattern + to.enableVibration(from.shouldVibrate()) + to.setShowBadge(from.canShowBadge()) + to.lockscreenVisibility = from.lockscreenVisibility + to.setBypassDnd(from.canBypassDnd()) + } + + private fun createCallsNotificationChannel( + context: Context, + channelId: String, + soundUri: Uri?, + copySettingsFrom: NotificationChannel? = null + ) { val audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) @@ -124,7 +147,8 @@ object NotificationUtils { true ), soundUri, - audioAttributes + audioAttributes, + copySettingsFrom ) } @@ -157,8 +181,8 @@ object NotificationUtils { */ fun updateCallRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?): Boolean { val baseId = NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name - val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId -> - createCallsNotificationChannel(context, channelId, ringtoneUri) + val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId, currentChannel -> + createCallsNotificationChannel(context, channelId, ringtoneUri, currentChannel) } if (replaced) { appPreferences.callRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) @@ -172,8 +196,8 @@ object NotificationUtils { */ fun updateMessageRingtone(context: Context, appPreferences: AppPreferences, ringtoneUri: Uri?): Boolean { val baseId = NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name - val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId -> - createMessagesNotificationChannel(context, channelId, ringtoneUri) + val replaced = replaceChannel(context, baseId, ringtoneUri) { channelId, currentChannel -> + createMessagesNotificationChannel(context, channelId, ringtoneUri, currentChannel) } if (replaced) { appPreferences.messageRingtoneUri = LoganSquare.serialize(RingtoneSettings(ringtoneUri, null)) @@ -182,15 +206,15 @@ object NotificationUtils { } /** - * Creates a new channel with a new id and then deletes the old ones. Other settings the user changed in the - * system settings for the old channel are not kept. + * Creates a new channel with a new id, based on the settings of the current channel, and then deletes the old + * ones. */ @Suppress("TooGenericExceptionCaught") private fun replaceChannel( context: Context, baseId: String, sound: Uri?, - createChannel: (String) -> Unit + createChannel: (channelId: String, currentChannel: NotificationChannel?) -> Unit ): Boolean { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val oldChannels = notificationManager.notificationChannels.filter { channelVersion(it.id, baseId) != null } @@ -198,9 +222,10 @@ object NotificationUtils { return true } + val currentChannel = oldChannels.maxByOrNull { channelVersion(it.id, baseId) ?: 0L } val newChannelId = baseId + CHANNEL_ID_VERSION_SEPARATOR + System.currentTimeMillis() val created = try { - createChannel(newChannelId) + createChannel(newChannelId, currentChannel) true } catch (e: RuntimeException) { // e.g. SecurityException for sounds the app is not allowed to read, or invalid sound uris @@ -233,7 +258,12 @@ object NotificationUtils { ) } - private fun createMessagesNotificationChannel(context: Context, channelId: String, soundUri: Uri?) { + private fun createMessagesNotificationChannel( + context: Context, + channelId: String, + soundUri: Uri?, + copySettingsFrom: NotificationChannel? = null + ) { val audioAttributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) @@ -249,7 +279,8 @@ object NotificationUtils { true ), soundUri, - audioAttributes + audioAttributes, + copySettingsFrom ) } From 4316cbd6277094ed33506ca8b86c0e51249d3792 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Tue, 17 Nov 2026 20:21:45 +0100 Subject: [PATCH 7/7] refactor(notifications): port sound selection to the compose settings screen The settings screen was migrated to Compose, so the sound dialog is now a composable and the sound change runs in the SettingsViewModel on a coroutine. The system ringtone picker is opened through an ActivityResultContract, and the system notification settings open the current, versioned channel. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Marcel Hibbe --- .../talk/settings/DeviceStateReader.kt | 9 +- .../talk/settings/NotificationSoundUpdater.kt | 31 ++++ .../talk/settings/PickSoundContract.kt | 56 +++++++ .../talk/settings/SettingsActivity.kt | 36 +++- .../talk/settings/SettingsUiState.kt | 19 ++- .../talk/settings/SettingsViewModel.kt | 12 ++ .../talk/settings/ui/SettingsDialogs.kt | 6 +- .../ui/SettingsNotificationsSection.kt | 61 +++++-- .../talk/settings/ui/SettingsScreen.kt | 6 + .../talk/settings/ui/SettingsSoundDialog.kt | 154 ++++++++++++++++++ .../talk/settings/SettingsViewModelTest.kt | 30 ++++ 11 files changed, 393 insertions(+), 27 deletions(-) create mode 100644 app/src/main/java/com/nextcloud/talk/settings/NotificationSoundUpdater.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/PickSoundContract.kt create mode 100644 app/src/main/java/com/nextcloud/talk/settings/ui/SettingsSoundDialog.kt diff --git a/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt b/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt index 9cad25dd89d..531c2e50083 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/DeviceStateReader.kt @@ -83,8 +83,11 @@ class DeviceStateReader @Inject constructor( ringtoneUri == null -> RingtoneState.Silent ringtoneUri.toString() == NotificationUtils.DEFAULT_CALL_RINGTONE_URI || ringtoneUri.toString() == NotificationUtils.DEFAULT_MESSAGE_RINGTONE_URI -> RingtoneState.Default - else -> RingtoneManager.getRingtone(context, ringtoneUri)?.getTitle(context) - ?.let { RingtoneState.Custom(it) } - ?: RingtoneState.Default + else -> RingtoneState.Custom( + title = RingtoneManager.getRingtone(context, ringtoneUri)?.getTitle(context) + ?: ringtoneUri.lastPathSegment + ?: ringtoneUri.toString(), + uri = ringtoneUri.toString() + ) } } diff --git a/app/src/main/java/com/nextcloud/talk/settings/NotificationSoundUpdater.kt b/app/src/main/java/com/nextcloud/talk/settings/NotificationSoundUpdater.kt new file mode 100644 index 00000000000..e8586e067f7 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/NotificationSoundUpdater.kt @@ -0,0 +1,31 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.settings + +import android.content.Context +import androidx.annotation.WorkerThread +import androidx.core.net.toUri +import com.nextcloud.talk.utils.NotificationUtils +import com.nextcloud.talk.utils.preferences.AppPreferences +import javax.inject.Inject + +/** Changes the sound of a notification channel, which recreates the channel. */ +class NotificationSoundUpdater @Inject constructor( + private val context: Context, + private val appPreferences: AppPreferences +) { + /** + * @param uri null for no sound + * @return false if the sound could not be set + */ + @WorkerThread + fun update(sound: NotificationSound, uri: String?): Boolean = + when (sound) { + NotificationSound.CALL -> NotificationUtils.updateCallRingtone(context, appPreferences, uri?.toUri()) + NotificationSound.MESSAGE -> NotificationUtils.updateMessageRingtone(context, appPreferences, uri?.toUri()) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/PickSoundContract.kt b/app/src/main/java/com/nextcloud/talk/settings/PickSoundContract.kt new file mode 100644 index 00000000000..031d82ef25b --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/PickSoundContract.kt @@ -0,0 +1,56 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.settings + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.media.RingtoneManager +import android.net.Uri +import android.provider.Settings +import androidx.activity.result.contract.ActivityResultContract +import androidx.core.content.IntentCompat +import androidx.core.net.toUri + +/** Opens the system ringtone picker. */ +class PickSoundContract : ActivityResultContract() { + + /** + * @param existingUri the sound selected in the picker, null for no sound + */ + data class Request(val sound: NotificationSound, val title: String, val existingUri: String?) + + /** @param uri the picked sound, null for no sound */ + data class Result(val uri: String?) + + override fun createIntent(context: Context, input: Request): Intent { + val (ringtoneType, systemDefaultUri) = when (input.sound) { + NotificationSound.CALL -> RingtoneManager.TYPE_RINGTONE to Settings.System.DEFAULT_RINGTONE_URI + NotificationSound.MESSAGE -> RingtoneManager.TYPE_NOTIFICATION to Settings.System.DEFAULT_NOTIFICATION_URI + } + return Intent(RingtoneManager.ACTION_RINGTONE_PICKER) + .putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, ringtoneType) + .putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, input.title) + .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true) + .putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, systemDefaultUri) + .putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true) + .putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, input.existingUri?.toUri()) + } + + /** @return null if nothing was picked; a missing extra must not be treated as "no sound" */ + override fun parseResult(resultCode: Int, intent: Intent?): Result? { + if (resultCode != Activity.RESULT_OK || intent?.hasExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI) != true) { + return null + } + val pickedUri = IntentCompat.getParcelableExtra( + intent, + RingtoneManager.EXTRA_RINGTONE_PICKED_URI, + Uri::class.java + ) + return Result(pickedUri?.toString()) + } +} diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt index 088e53e6eb7..3f7710e0a67 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt @@ -47,6 +47,8 @@ import com.nextcloud.talk.settings.ui.ProxyCallbacks import com.nextcloud.talk.settings.ui.SettingsScreen import com.nextcloud.talk.settings.ui.SettingsScreenCallbacks import com.nextcloud.talk.settings.ui.SystemSettingsScreen +import com.nextcloud.talk.settings.ui.systemSettingsScreen +import com.nextcloud.talk.settings.ui.titleRes import com.nextcloud.talk.utils.LoggingUtils.sendMailWithAttachment import com.nextcloud.talk.utils.NotificationUtils import com.nextcloud.talk.utils.UnifiedPushUtils @@ -101,6 +103,10 @@ class SettingsActivity : BaseActivity() { } } + private val callSoundPickerLauncher = registerSoundPicker(NotificationSound.CALL) + + private val messageSoundPickerLauncher = registerSoundPicker(NotificationSound.MESSAGE) + private val contactsPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { results -> if (results.isNotEmpty() && results.values.all { it }) { @@ -157,6 +163,8 @@ class SettingsActivity : BaseActivity() { }, onOpenSystemSettings = ::openSystemSettings, onOpenDiagnosis = { startActivity(intentForAccount(DiagnosisActivity::class.java)) }, + onPickNotificationSound = ::pickNotificationSound, + onNotificationSoundChange = viewModel::setNotificationSound, onShowNotificationWarningChange = viewModel::setShowNotificationWarning, onScreenLockChange = viewModel::setScreenLock, onScreenLockTimeoutChange = viewModel::setScreenLockTimeout, @@ -267,11 +275,9 @@ class SettingsActivity : BaseActivity() { Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, "package:$packageName".toUri()) } SystemSettingsScreen.CALL_NOTIFICATIONS -> - notificationChannelSettingsIntent(NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5) + notificationChannelSettingsIntent(NotificationUtils.getCallsNotificationChannelId(this)) SystemSettingsScreen.MESSAGE_NOTIFICATIONS -> - notificationChannelSettingsIntent( - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4 - ) + notificationChannelSettingsIntent(NotificationUtils.getMessagesNotificationChannelId(this)) } openSystemSettings(intent) } @@ -284,10 +290,28 @@ class SettingsActivity : BaseActivity() { } } - private fun notificationChannelSettingsIntent(channel: NotificationUtils.NotificationChannels): Intent = + private fun notificationChannelSettingsIntent(channelId: String): Intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) .putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) - .putExtra(Settings.EXTRA_CHANNEL_ID, channel.name) + .putExtra(Settings.EXTRA_CHANNEL_ID, channelId) + + private fun registerSoundPicker(sound: NotificationSound) = + registerForActivityResult(PickSoundContract()) { result -> + result?.let { viewModel.setNotificationSound(sound, it.uri) } + } + + private fun pickNotificationSound(sound: NotificationSound, current: RingtoneState) { + val launcher = when (sound) { + NotificationSound.CALL -> callSoundPickerLauncher + NotificationSound.MESSAGE -> messageSoundPickerLauncher + } + try { + launcher.launch(PickSoundContract.Request(sound, getString(sound.titleRes), sound.uriOf(current))) + } catch (e: ActivityNotFoundException) { + Log.w(TAG, "No ringtone picker available, opening the notification channel settings instead", e) + openSystemSettings(sound.systemSettingsScreen) + } + } private fun openLogs() { startActivity(Intent(this, LogsActivity::class.java)) diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt index eb060b40398..fafcb51da7d 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsUiState.kt @@ -7,6 +7,7 @@ package com.nextcloud.talk.settings import androidx.compose.runtime.Immutable +import com.nextcloud.talk.utils.NotificationUtils @Immutable data class SettingsUiState( @@ -91,8 +92,24 @@ sealed interface RingtoneState { /** The notification channel is turned off. */ data object Disabled : RingtoneState data object Silent : RingtoneState + + /** The sound bundled with the app, which the system ringtone picker doesn't list. */ data object Default : RingtoneState - data class Custom(val title: String) : RingtoneState + data class Custom(val title: String, val uri: String) : RingtoneState +} + +/** The notification sounds that can be chosen on the settings screen. */ +enum class NotificationSound(private val bundledUri: String, val audioUsage: Int) { + CALL(NotificationUtils.DEFAULT_CALL_RINGTONE_URI, NotificationUtils.CALLS_AUDIO_USAGE), + MESSAGE(NotificationUtils.DEFAULT_MESSAGE_RINGTONE_URI, NotificationUtils.MESSAGES_AUDIO_USAGE); + + /** The uri of the sound that [ringtone] stands for, null for no sound. */ + fun uriOf(ringtone: RingtoneState): String? = + when (ringtone) { + RingtoneState.Default -> bundledUri + is RingtoneState.Custom -> ringtone.uri + RingtoneState.Silent, RingtoneState.Disabled -> null + } } @Immutable diff --git a/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt index b276561cbf7..e90e7adab75 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsViewModel.kt @@ -59,6 +59,7 @@ class SettingsViewModel @AssistedInject constructor( private val settingsRepository: SettingsRepository, private val logsRepository: LogsRepository, private val deviceStateReader: DeviceStateReader, + private val notificationSoundUpdater: NotificationSoundUpdater, private val accountRemover: AccountRemover, private val workManager: WorkManager, private val logger: Logger, @@ -207,6 +208,17 @@ class SettingsViewModel @AssistedInject constructor( } } + /** @param uri null for no sound */ + fun setNotificationSound(sound: NotificationSound, uri: String?) { + viewModelScope.launch { + val updated = withContext(preferenceWriter) { notificationSoundUpdater.update(sound, uri) } + if (!updated) { + _events.send(SettingsEvent.ShowMessage(R.string.nc_common_error_sorry)) + } + refreshDeviceState() + } + } + fun setShowNotificationWarning(show: Boolean) { _uiState.update { it.copy(notifications = it.notifications.copy(showNotificationWarning = show)) } persist { prefs -> diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt index 19bf9f92dbe..41b52b5a2d4 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsDialogs.kt @@ -114,12 +114,12 @@ internal fun MediaQualityDialog(reducedQuality: Boolean, onSelect: (Boolean) -> style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 8.dp) ) - MediaQualityOption( + RadioOption( label = stringResource(R.string.nc_media_quality_original), selected = !reducedQuality, onClick = { onSelect(false) } ) - MediaQualityOption( + RadioOption( label = stringResource(R.string.nc_media_quality_reduced), selected = reducedQuality, onClick = { onSelect(true) } @@ -134,7 +134,7 @@ internal fun MediaQualityDialog(reducedQuality: Boolean, onSelect: (Boolean) -> } @Composable -private fun MediaQualityOption(label: String, selected: Boolean, onClick: () -> Unit) { +internal fun RadioOption(label: String, selected: Boolean, onClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt index 56c7971a636..744ce7429c1 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsNotificationsSection.kt @@ -7,6 +7,7 @@ package com.nextcloud.talk.settings.ui import android.content.res.Configuration +import androidx.annotation.StringRes import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Column import androidx.compose.material3.MaterialTheme @@ -23,6 +24,7 @@ import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.nextcloud.talk.R +import com.nextcloud.talk.settings.NotificationSound import com.nextcloud.talk.settings.NotificationsUiState import com.nextcloud.talk.settings.PushAvailability import com.nextcloud.talk.settings.RingtoneState @@ -203,22 +205,53 @@ private fun TroubleshootingDialog(onOpenDiagnosis: () -> Unit, onDismiss: () -> @Composable private fun RingtoneItems(state: NotificationsUiState, highlightIssues: Boolean, callbacks: SettingsScreenCallbacks) { - RingtoneItem( - title = stringResource(R.string.nc_settings_call_ringtone), - ringtone = state.callRingtone, - enabled = state.ringtoneSettingsEnabled, - highlight = highlightIssues, - onClick = { callbacks.onOpenSystemSettings(SystemSettingsScreen.CALL_NOTIFICATIONS) } - ) - RingtoneItem( - title = stringResource(R.string.nc_settings_other_notifications_ringtone), - ringtone = state.messageRingtone, - enabled = state.ringtoneSettingsEnabled, - highlight = highlightIssues, - onClick = { callbacks.onOpenSystemSettings(SystemSettingsScreen.MESSAGE_NOTIFICATIONS) } - ) + var soundDialog by rememberSaveable { mutableStateOf(null) } + + NotificationSound.entries.forEach { sound -> + val ringtone = state.ringtone(sound) + RingtoneItem( + title = stringResource(sound.titleRes), + ringtone = ringtone, + enabled = state.ringtoneSettingsEnabled, + highlight = highlightIssues, + onClick = { + if (ringtone == RingtoneState.Disabled) { + callbacks.onOpenSystemSettings(sound.systemSettingsScreen) + } else { + soundDialog = sound + } + } + ) + } + + soundDialog?.let { sound -> + SoundDialog( + sound = sound, + current = state.ringtone(sound), + callbacks = callbacks, + onDismiss = { soundDialog = null } + ) + } } +private fun NotificationsUiState.ringtone(sound: NotificationSound): RingtoneState = + when (sound) { + NotificationSound.CALL -> callRingtone + NotificationSound.MESSAGE -> messageRingtone + } + +internal val NotificationSound.systemSettingsScreen: SystemSettingsScreen + get() = when (this) { + NotificationSound.CALL -> SystemSettingsScreen.CALL_NOTIFICATIONS + NotificationSound.MESSAGE -> SystemSettingsScreen.MESSAGE_NOTIFICATIONS + } + +internal val NotificationSound.titleRes: Int + @StringRes get() = when (this) { + NotificationSound.CALL -> R.string.nc_settings_call_ringtone + NotificationSound.MESSAGE -> R.string.nc_settings_other_notifications_ringtone + } + @Composable private fun RingtoneItem( title: String, diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt index 29401b7a955..5aa7fd02f87 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsScreen.kt @@ -44,6 +44,7 @@ import com.nextcloud.talk.components.ColoredStatusBar import com.nextcloud.talk.components.IncognitoKeyboard import com.nextcloud.talk.components.StandardAppBar import com.nextcloud.talk.settings.AccountUiState +import com.nextcloud.talk.settings.NotificationSound import com.nextcloud.talk.settings.NotificationsUiState import com.nextcloud.talk.settings.PrivacyUiState import com.nextcloud.talk.settings.ProxyUiState @@ -72,6 +73,11 @@ data class SettingsScreenCallbacks( val onRequestNotificationPermission: () -> Unit = {}, val onOpenSystemSettings: (SystemSettingsScreen) -> Unit = {}, val onOpenDiagnosis: () -> Unit = {}, + /** Opens the system ringtone picker, with the current sound selected. */ + val onPickNotificationSound: (NotificationSound, RingtoneState) -> Unit = { _, _ -> }, + + /** Sets the sound by its uri, null for no sound. */ + val onNotificationSoundChange: (NotificationSound, String?) -> Unit = { _, _ -> }, val onShowNotificationWarningChange: (Boolean) -> Unit = {}, val onScreenLockChange: (Boolean) -> Unit = {}, val onScreenLockTimeoutChange: (String) -> Unit = {}, diff --git a/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsSoundDialog.kt b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsSoundDialog.kt new file mode 100644 index 00000000000..81b6a7e7e07 --- /dev/null +++ b/app/src/main/java/com/nextcloud/talk/settings/ui/SettingsSoundDialog.kt @@ -0,0 +1,154 @@ +/* + * Nextcloud Talk - Android Client + * + * SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ +package com.nextcloud.talk.settings.ui + +import android.content.Context +import android.content.res.Configuration +import android.media.AudioAttributes +import android.media.Ringtone +import android.media.RingtoneManager +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.core.net.toUri +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import com.nextcloud.talk.R +import com.nextcloud.talk.settings.NotificationSound +import com.nextcloud.talk.settings.RingtoneState + +/** + * Lets the user choose the sound of [sound]. Besides the current sound and no sound, it offers the sound bundled with + * the app, which the system ringtone picker doesn't list. + */ +@Composable +internal fun SoundDialog( + sound: NotificationSound, + current: RingtoneState, + callbacks: SettingsScreenCallbacks, + onDismiss: () -> Unit +) { + val options = listOfNotNull(RingtoneState.Default, current as? RingtoneState.Custom, RingtoneState.Silent) + var selectedIndex by rememberSaveable { mutableIntStateOf(options.indexOf(current)) } + val previewPlayer = rememberSoundPreviewPlayer() + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(sound.titleRes)) }, + text = { + Column(modifier = Modifier.selectableGroup().verticalScroll(rememberScrollState())) { + options.forEachIndexed { index, option -> + RadioOption(label = soundLabel(option), selected = index == selectedIndex, onClick = { + selectedIndex = index + previewPlayer.stop() + sound.uriOf(option)?.let { previewPlayer.play(it, sound.audioUsage) } + }) + } + RadioOption(label = stringResource(R.string.nc_settings_other_sound), selected = false, onClick = { + previewPlayer.stop() + onDismiss() + callbacks.onPickNotificationSound(sound, current) + }) + } + }, + confirmButton = { + TextButton(onClick = { + onDismiss() + val selected = options.getOrNull(selectedIndex) + if (selected != null && selected != current) { + callbacks.onNotificationSoundChange(sound, sound.uriOf(selected)) + } + }) { Text(stringResource(R.string.nc_ok)) } + }, + dismissButton = { + Row { + TextButton(onClick = { + onDismiss() + callbacks.onOpenSystemSettings(sound.systemSettingsScreen) + }) { + Text(stringResource(R.string.nc_notification_settings)) + } + TextButton(onClick = onDismiss) { Text(stringResource(R.string.nc_cancel)) } + } + } + ) +} + +@Composable +private fun soundLabel(ringtone: RingtoneState): String = + when (ringtone) { + RingtoneState.Default -> stringResource(R.string.nc_settings_default_ringtone) + RingtoneState.Silent, RingtoneState.Disabled -> stringResource(R.string.nc_settings_no_ringtone) + is RingtoneState.Custom -> ringtone.title + } + +/** Plays one sound at a time, to preview it. */ +internal class SoundPreviewPlayer(private val context: Context) { + private var ringtone: Ringtone? = null + + fun play(uri: String, audioUsage: Int) { + stop() + ringtone = RingtoneManager.getRingtone(context, uri.toUri())?.apply { + audioAttributes = AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(audioUsage) + .build() + play() + } + } + + fun stop() { + ringtone?.stop() + ringtone = null + } +} + +/** A [SoundPreviewPlayer] that stops when it leaves the composition or the screen is paused. */ +@Composable +internal fun rememberSoundPreviewPlayer(): SoundPreviewPlayer { + val context = LocalContext.current + val player = remember(context) { SoundPreviewPlayer(context) } + DisposableEffect(player) { + onDispose { player.stop() } + } + LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { player.stop() } + return player +} + +@Preview(name = "Light") +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) +@Composable +private fun SoundDialogPreview() { + MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) { + SoundDialog( + sound = NotificationSound.CALL, + current = RingtoneState.Custom("Ring", "content://media/internal/audio/media/1"), + callbacks = SettingsScreenCallbacks(), + onDismiss = {} + ) + } +} diff --git a/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt index de3f9ce826d..d35d2f0f19a 100644 --- a/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt +++ b/app/src/test/java/com/nextcloud/talk/settings/SettingsViewModelTest.kt @@ -83,6 +83,7 @@ class SettingsViewModelTest { private lateinit var context: Context private val repository = FakeSettingsRepository() private val accountRemover = mock() + private val notificationSoundUpdater = mock() private var deviceState = DEVICE_STATE @Before @@ -132,6 +133,7 @@ class SettingsViewModelTest { settingsRepository = repository, logsRepository = logsRepository, deviceStateReader = mock { on { read() } doAnswer { deviceState } }, + notificationSoundUpdater = notificationSoundUpdater, accountRemover = accountRemover, workManager = workManager, logger = mock(), @@ -387,6 +389,33 @@ class SettingsViewModelTest { assertEquals("60", privacy.screenLockTimeout) } + @Test + fun `changed notification sound is shown`() { + whenever(notificationSoundUpdater.update(NotificationSound.CALL, SOUND_URI)) doAnswer { + deviceState = DEVICE_STATE.copy(callRingtone = RingtoneState.Custom("Ring", SOUND_URI)) + true + } + val viewModel = createViewModel() + + viewModel.setNotificationSound(NotificationSound.CALL, SOUND_URI) + dispatcher.scheduler.advanceUntilIdle() + + verify(notificationSoundUpdater).update(NotificationSound.CALL, SOUND_URI) + assertEquals(RingtoneState.Custom("Ring", SOUND_URI), viewModel.uiState.value.notifications.callRingtone) + } + + @Test + fun `failed notification sound change shows an error`() = + runTest(dispatcher) { + whenever(notificationSoundUpdater.update(NotificationSound.MESSAGE, null)) doReturn false + val viewModel = createViewModel() + + viewModel.setNotificationSound(NotificationSound.MESSAGE, null) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(SettingsEvent.ShowMessage(R.string.nc_common_error_sorry), viewModel.events.first()) + } + @Test fun `cancelled certificate choice keeps the stored certificate`() { val viewModel = createViewModel(user.copy(clientCertificate = "alias")) @@ -471,6 +500,7 @@ class SettingsViewModelTest { private const val USER_ID = 1L private const val NO_PROXY = "No proxy" private const val TIMEOUT_MS = 1000L + private const val SOUND_URI = "content://media/internal/audio/media/1" private val DEVICE_STATE = DeviceState( isGooglePlayServicesAvailable = true, hasEmbeddedDistributor = false,