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 b21b1ad4b92..9b8aea2ac3b 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 @@ -770,7 +770,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) ) } } @@ -1219,8 +1219,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/settings/SettingsActivity.kt b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt index a78db86faaa..85537e84323 100644 --- a/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/settings/SettingsActivity.kt @@ -16,6 +16,7 @@ import android.animation.AnimatorListenerAdapter import android.annotation.SuppressLint import android.app.KeyguardManager import android.app.NotificationManager +import android.content.ActivityNotFoundException import android.content.Context import android.content.DialogInterface import android.content.Intent @@ -32,11 +33,13 @@ import android.util.Log import android.view.View import android.view.WindowManager import android.widget.Toast +import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.core.content.ContextCompat +import androidx.core.content.IntentCompat import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.drawable.toDrawable import androidx.core.net.toUri @@ -152,6 +155,14 @@ class SettingsActivity : } } + private val callRingtonePickerLauncher = registerSoundPickerLauncher { uri -> + NotificationUtils.updateCallRingtone(context, appPreferences, uri) + } + + private val messageRingtonePickerLauncher = registerSoundPickerLauncher { uri -> + NotificationUtils.updateMessageRingtone(context, appPreferences, uri) + } + private var currentUser: User? = null private var credentials: String? = null private lateinit var proxyTypeFlow: Flow @@ -597,25 +608,130 @@ class SettingsActivity : } } - binding.settingsCallSound.setOnClickListener { - val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) - intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) - intent.putExtra( - Settings.EXTRA_CHANNEL_ID, - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5.name - ) + binding.settingsCallSound.setOnClickListener { onCallSoundClicked() } + binding.settingsMessageSound.setOnClickListener { onMessageSoundClicked() } + } - startActivity(intent) + private fun onCallSoundClicked() { + if (NotificationUtils.isCallsNotificationChannelEnabled(context)) { + showSoundDialog( + R.string.nc_settings_call_ringtone, + onDefaultSelected = { + NotificationUtils.updateCallRingtone( + context, + appPreferences, + NotificationUtils.DEFAULT_CALL_RINGTONE_URI.toUri() + ) + }, + onOtherSelected = { + openSoundPicker( + callRingtonePickerLauncher, + RingtoneManager.TYPE_RINGTONE, + R.string.nc_settings_call_ringtone, + Settings.System.DEFAULT_RINGTONE_URI, + getCallRingtoneUri(context, appPreferences), + NotificationUtils.getCallsNotificationChannelId(context) + ) + } + ) + } else { + openChannelSettings(NotificationUtils.getCallsNotificationChannelId(context)) } - binding.settingsMessageSound.setOnClickListener { - val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) - intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) - intent.putExtra( - Settings.EXTRA_CHANNEL_ID, - NotificationUtils.NotificationChannels.NOTIFICATION_CHANNEL_MESSAGES_V4.name + } + + private fun onMessageSoundClicked() { + if (NotificationUtils.isMessagesNotificationChannelEnabled(context)) { + showSoundDialog( + R.string.nc_settings_other_notifications_ringtone, + onDefaultSelected = { + NotificationUtils.updateMessageRingtone( + context, + appPreferences, + NotificationUtils.DEFAULT_MESSAGE_RINGTONE_URI.toUri() + ) + }, + onOtherSelected = { + openSoundPicker( + messageRingtonePickerLauncher, + RingtoneManager.TYPE_NOTIFICATION, + R.string.nc_settings_other_notifications_ringtone, + Settings.System.DEFAULT_NOTIFICATION_URI, + getMessageRingtoneUri(context, appPreferences), + NotificationUtils.getMessagesNotificationChannelId(context) + ) + } ) - startActivity(intent) + } else { + openChannelSettings(NotificationUtils.getMessagesNotificationChannelId(context)) + } + } + + private fun registerSoundPickerLauncher(onPicked: (Uri?) -> Unit) = + registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + if (result.resultCode == RESULT_OK) { + val pickedUri = result.data?.let { + IntentCompat.getParcelableExtra(it, RingtoneManager.EXTRA_RINGTONE_PICKED_URI, Uri::class.java) + } + onPicked(pickedUri) + setupNotificationSoundsSettings() + } } + + /** + * Sounds are chosen in-app instead of in the system channel settings, because the bundled default sounds are + * not part of the system sounds, and some OEMs (e.g. Samsung) only offer notification sounds for the calls + * channel. + */ + private fun showSoundDialog(titleRes: Int, onDefaultSelected: () -> Unit, onOtherSelected: () -> Unit) { + val items = arrayOf( + getString(R.string.nc_settings_default_ringtone), + getString(R.string.nc_settings_other_sound) + ) + val dialogBuilder = MaterialAlertDialogBuilder(this) + .setTitle(titleRes) + .setItems(items) { _, which -> + if (which == 0) { + onDefaultSelected() + setupNotificationSoundsSettings() + } else { + onOtherSelected() + } + } + .setNegativeButton(R.string.nc_cancel, null) + viewThemeUtils.dialog.colorMaterialAlertDialogBackground(this, dialogBuilder) + val dialog = dialogBuilder.show() + viewThemeUtils.platform.colorTextButtons(dialog.getButton(AlertDialog.BUTTON_NEGATIVE)) + } + + @Suppress("LongParameterList") + private fun openSoundPicker( + launcher: ActivityResultLauncher, + ringtoneType: Int, + titleRes: Int, + systemDefaultUri: Uri, + existingUri: Uri?, + fallbackChannelId: String + ) { + val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER) + .putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, ringtoneType) + .putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, getString(titleRes)) + .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, existingUri) + try { + launcher.launch(intent) + } catch (e: ActivityNotFoundException) { + Log.w(TAG, "No ringtone picker available, falling back to channel settings", e) + openChannelSettings(fallbackChannelId) + } + } + + private fun openChannelSettings(channelId: String) { + val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS) + intent.putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID) + intent.putExtra(Settings.EXTRA_CHANNEL_ID, channelId) + startActivity(intent) } private fun setTroubleshootingClickListenersIfNecessary() { 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..ecb23d21922 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 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. + */ + private const val CHANNEL_ID_VERSION_SEPARATOR = "__" + private fun createNotificationChannel( context: Context, notificationChannel: Channel, @@ -99,27 +115,127 @@ 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 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 = + 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. + */ + 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) + } + } + + /** + * 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) + } + } + + /** + * 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 + } + /** * Separate from [NotificationChannels.NOTIFICATION_CHANNEL_CALLS_V5] (the incoming-ring channel, * which must stay IMPORTANCE_HIGH) so the persistent "call in progress" foreground-service @@ -139,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() ) } @@ -193,7 +310,7 @@ object NotificationUtils { // Delete all notification channels created by previous versions for (channel in notificationManager.notificationChannels) { - if (!channelsToKeep.contains(channel.id)) { + if (channelsToKeep.none { isVersionedChannelId(channel.id, it) }) { notificationManager.deleteNotificationChannel(channel.id) } } @@ -286,7 +403,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) } @@ -294,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) } @@ -340,7 +457,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? = @@ -348,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 8a17dc00159..784f9de4f02 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