From 66d74aea53d1d0f6e5605bca44c8c04087cabb6b Mon Sep 17 00:00:00 2001 From: Tomasz Swistak Date: Sun, 29 Nov 2026 12:12:50 +0100 Subject: [PATCH 1/6] fix: notification audio channel change reliability --- CHANGELOG.md | 4 + .../alarms/AlarmDatabaseInstrumentedTest.kt | 59 ++- .../GeneralBackupInstrumentedTest.kt | 6 +- .../MonitoringRegressionInstrumentedTest.kt | 33 +- .../AlarmNotificationsInstrumentedTest.kt | 16 +- .../monitoring/BatteryInfoService.kt | 119 ++++-- .../monitoring/ThresholdAlarmEvaluator.kt | 38 +- .../notifications/AlarmNotifications.kt | 127 +++++-- .../notifications/NotificationChannels.kt | 347 ++++++++++++------ .../ui/alarms/AlarmsViewModel.kt | 18 +- .../alarms/backup/AlarmChannelRestoreTest.kt | 184 ++++++++++ .../monitoring/ThresholdAlarmEvaluatorTest.kt | 18 +- .../notifications/NotificationChannelsTest.kt | 297 ++++++++++++++- 13 files changed, 1036 insertions(+), 230 deletions(-) create mode 100644 app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 21d5f2e9..5267e98a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Improved + +- Notification audio channel change reliability. + ### Fixed - Support for monochrome system color palette (#199). diff --git a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt index 8ae93a75..3c52fe9f 100644 --- a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt @@ -13,9 +13,12 @@ package codes.swistak.batterymonitor.alarms import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager import android.content.Context import android.content.ContextWrapper import android.database.sqlite.SQLiteDatabase +import android.media.AudioAttributes import android.net.Uri import android.os.Bundle import androidx.lifecycle.SavedStateHandle @@ -23,6 +26,7 @@ import androidx.test.platform.app.InstrumentationRegistry import codes.swistak.batterymonitor.R import codes.swistak.batterymonitor.alarms.backup.AlarmBackup import codes.swistak.batterymonitor.alarms.backup.Version2AlarmImporter +import codes.swistak.batterymonitor.monitoring.notifications.NotificationChannels import codes.swistak.batterymonitor.testsupport.awaitCondition import codes.swistak.batterymonitor.testsupport.runOnMain import codes.swistak.batterymonitor.ui.alarms.AlarmDraft @@ -40,10 +44,12 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Assert.fail +import org.junit.Assume.assumeFalse import org.junit.Before import org.junit.Test import java.io.File import java.util.Locale +import java.util.UUID import java.util.concurrent.atomic.AtomicInteger class AlarmDatabaseInstrumentedTest { @@ -90,6 +96,49 @@ class AlarmDatabaseInstrumentedTest { ).use { it.execSQL(statement) } } + @Test + fun switching_stream_on_a_blocked_silent_channel_preserves_both_settings_in_android() { + val type = "charge_drops" + val manager = context.getSystemService(NotificationManager::class.java) + assumeFalse( + "The isolated alarm database requires a clean notification environment", + manager.notificationChannels.any { it.id.startsWith("alarm_settings_") } || + manager.activeNotifications.any { + it.id == 7 && (it.tag == null || it.tag.startsWith( + "alarm:" + )) + } + ) + val source = NotificationChannel( + "test-blocked-${UUID.randomUUID()}", + "Blocked source", + NotificationManager.IMPORTANCE_NONE + ).apply { setSound(null, null) } + val original = AlarmConfiguration(channelId = source.id) + try { + manager.createNotificationChannel(source) + database.saveSharedSettings(type, null, original) + NotificationChannels.saveAlarmSettings( + context, database, type, null, original, + AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS), + replacementConfirmed = true + ) + val channelId = requireNotNull(database.getSnapshot().shared.getValue(type).channelId) + assertFalse(source.id == channelId) + val registered = requireNotNull(manager.getNotificationChannel(channelId)) + assertEquals(NotificationManager.IMPORTANCE_NONE, registered.importance) + assertNull(registered.sound) + assertEquals(AudioAttributes.USAGE_ALARM, registered.audioAttributes.usage) + assertEquals( + AudioAttributes.CONTENT_TYPE_SONIFICATION, + registered.audioAttributes.contentType + ) + } finally { + database.getSnapshot().shared[type]?.channelId?.let(manager::deleteNotificationChannel) + manager.deleteNotificationChannel(source.id) + } + } + @Test fun reads_never_create_events_and_first_on_creates_only_one_persistent_record() { assertTrue(rows().isEmpty()) @@ -247,13 +296,13 @@ class AlarmDatabaseInstrumentedTest { """CREATE TABLE alarms (_id INTEGER PRIMARY KEY, enabled INTEGER, type STRING, threshold STRING, ringtone STRING, vibrate INTEGER, lights INTEGER)""" ) - for (row in before) { + for ((id, enabled, type, threshold) in before) { legacy.execSQL( "INSERT INTO alarms VALUES (?,?,?,?,?,1,0)", arrayOf( - row.id, - if (row.enabled) 1 else 0, - row.type, - row.threshold, + id, + if (enabled) 1 else 0, + type, + threshold, "content://saved/tone" ) ) diff --git a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/devicebackup/GeneralBackupInstrumentedTest.kt b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/devicebackup/GeneralBackupInstrumentedTest.kt index 3d3c5437..bda380f0 100644 --- a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/devicebackup/GeneralBackupInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/devicebackup/GeneralBackupInstrumentedTest.kt @@ -185,9 +185,11 @@ class GeneralBackupInstrumentedTest { ) val restoredId = requireNotNull(snapshot.custom.getValue(custom.id).channelId) assertNotEquals(firstId, restoredId) + val attributes = + requireNotNull(manager.getNotificationChannel(restoredId)).audioAttributes + assertEquals(AudioAttributes.CONTENT_TYPE_SONIFICATION, attributes.contentType) assertEquals( - AudioAttributes.USAGE_MEDIA, - manager.getNotificationChannel(restoredId)?.audioAttributes?.usage + AudioAttributes.USAGE_MEDIA, attributes.usage ) val inherited = thresholds.getValue(21) assertEquals( diff --git a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/MonitoringRegressionInstrumentedTest.kt b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/MonitoringRegressionInstrumentedTest.kt index 3add4aab..63372df5 100644 --- a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/MonitoringRegressionInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/MonitoringRegressionInstrumentedTest.kt @@ -22,6 +22,7 @@ import android.content.ContextWrapper import android.content.Intent import android.database.DatabaseErrorHandler import android.database.sqlite.SQLiteDatabase +import android.media.AudioAttributes import android.os.Build import android.os.Handler import android.os.IBinder @@ -32,8 +33,10 @@ import android.os.SystemClock import androidx.core.content.pm.PackageInfoCompat import androidx.test.platform.app.InstrumentationRegistry import codes.swistak.batterymonitor.alarms.AlarmConfiguration -import codes.swistak.batterymonitor.alarms.AlarmRule +import codes.swistak.batterymonitor.alarms.AlarmDatabase import codes.swistak.batterymonitor.alarms.AlarmSnapshot +import codes.swistak.batterymonitor.alarms.AlarmSoundSettings +import codes.swistak.batterymonitor.alarms.AlarmVolumeCategory import codes.swistak.batterymonitor.app.BatteryInfoActivity import codes.swistak.batterymonitor.app.StartupDialogViewModel import codes.swistak.batterymonitor.common.DisplayStrings @@ -296,6 +299,8 @@ class MonitoringRegressionInstrumentedTest { set("alarmsPendingIntent", alarms) val notificationManager = target.getSystemService(NotificationManager::class.java) val channel = "alarm-navigation-${directory.name}" + val alarmDatabase = AlarmDatabase(context) + set("alarms", alarmDatabase) var activity: BatteryInfoActivity? = null try { assertTrue(MonitoringDesiredState.write(target, desired = false)) @@ -308,7 +313,11 @@ class MonitoringRegressionInstrumentedTest { notificationManager.createNotificationChannel( NotificationChannel( channel, channel, NotificationManager.IMPORTANCE_DEFAULT - ).apply { setSound(null, null) }) + ).apply { + val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build() + setSound(null, attributes) + }) val version = PackageInfoCompat.getLongVersionCode( target.packageManager.getPackageInfo(target.packageName, 0) ) @@ -328,9 +337,13 @@ class MonitoringRegressionInstrumentedTest { assertEquals(SectionOwner.ALARMS, navigator(launched).selected) } val type = "fully_charged" - val snapshot = AlarmSnapshot( - rules = listOf(AlarmRule(1, true, type, "")), - shared = mapOf(type to AlarmConfiguration(channelId = channel)) + alarmDatabase.setLogicalEnabled(type, emptyList(), true) + val snapshot = alarmDatabase.getSnapshot() + // The worker must use the channel saved after the battery reading was taken. + alarmDatabase.saveSharedSettings( + type, null, AlarmConfiguration( + AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS), channel + ) ) val handleAlarms = BatteryInfoService::class.java.getDeclaredMethod( "handleAlarms", @@ -364,6 +377,7 @@ class MonitoringRegressionInstrumentedTest { val notification = checkNotNull(posted) { "Fully charged alarm notification was not posted" } assertEquals(current, notification.contentIntent) + assertEquals(Notification.CATEGORY_ALARM, notification.category) notification.contentIntent.send() val deadline = SystemClock.elapsedRealtime() + 10_000L var selected = SectionOwner.ALARMS @@ -378,6 +392,7 @@ class MonitoringRegressionInstrumentedTest { instrumentation.runOnMainSync { activity?.finish() } instrumentation.waitForIdleSync() notificationManager.deleteNotificationChannel(channel) + alarmDatabase.close() current.cancel() alarms.cancel() assertTrue(MonitoringDesiredState.write(target, desiredBefore)) @@ -561,8 +576,8 @@ class MonitoringRegressionInstrumentedTest { }) val registration = currentClients().getValue(client) assertNull( - registration.javaClass.getDeclaredField("demand").apply { isAccessible = true } - .get(registration) + registration.javaClass.getDeclaredField("demand") + .apply { isAccessible = true }.get(registration) ) service.onUnbind(null) } @@ -586,8 +601,8 @@ class MonitoringRegressionInstrumentedTest { sendCurrentDemand(client, 1, 1, CurrentDemand(1_000, false)) val registration = currentClients().getValue(client) assertNull( - registration.javaClass.getDeclaredField("demand").apply { isAccessible = true } - .get(registration) + registration.javaClass.getDeclaredField("demand") + .apply { isAccessible = true }.get(registration) ) assertEquals(0, acquisitions) assertFalse(MonitoringDesiredState.read(context)) diff --git a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotificationsInstrumentedTest.kt b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotificationsInstrumentedTest.kt index 1ca153cc..2fe15d79 100644 --- a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotificationsInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotificationsInstrumentedTest.kt @@ -8,6 +8,7 @@ import android.app.NotificationManager import android.app.PendingIntent import android.content.ComponentName import android.content.Intent +import android.media.AudioAttributes import android.os.Build import android.os.Handler import android.os.Looper @@ -19,6 +20,7 @@ import codes.swistak.batterymonitor.alarms.AlarmPlayback import codes.swistak.batterymonitor.alarms.AlarmRule import codes.swistak.batterymonitor.alarms.AlarmSnapshot import codes.swistak.batterymonitor.alarms.AlarmSoundSettings +import codes.swistak.batterymonitor.alarms.AlarmVolumeCategory import codes.swistak.batterymonitor.monitoring.BatteryInfoService import codes.swistak.batterymonitor.monitoring.MonitoringDesiredState import org.junit.After @@ -46,7 +48,7 @@ class AlarmNotificationsInstrumentedTest { AlarmRule(inheritedId, true, type, "20"), AlarmRule(customId, true, type, "15") ), shared = mapOf(type to AlarmConfiguration(channelId = shared)), custom = mapOf( customId to AlarmConfiguration( - AlarmSoundSettings(AlarmPlayback.REPEAT), dedicated + AlarmSoundSettings(AlarmPlayback.REPEAT, AlarmVolumeCategory.ALARMS), dedicated ) ) ) @@ -71,7 +73,15 @@ class AlarmNotificationsInstrumentedTest { manager.createNotificationChannel( NotificationChannel( channel, channel, NotificationManager.IMPORTANCE_DEFAULT - ).apply { setSound(null, null) }) + ).apply { + val usage = if (channel == dedicated) AudioAttributes.USAGE_ALARM + else AudioAttributes.USAGE_NOTIFICATION + setSound( + null, + AudioAttributes.Builder().setUsage(usage) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build() + ) + }) } } @@ -86,6 +96,8 @@ class AlarmNotificationsInstrumentedTest { postBoth() val once = requireNotNull(active(shared)) val first = requireNotNull(active(dedicated)) + assertEquals(Notification.CATEGORY_ALARM, first.notification.category) + assertTrue(once.notification.category != Notification.CATEGORY_ALARM) assertFalse(once.notification.flags and Notification.FLAG_INSISTENT != 0) assertTrue(once.notification.actions.isNullOrEmpty()) assertTrue(first.notification.flags and Notification.FLAG_INSISTENT != 0) diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/BatteryInfoService.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/BatteryInfoService.kt index 90fadfdc..980240b0 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/BatteryInfoService.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/BatteryInfoService.kt @@ -493,7 +493,7 @@ class BatteryInfoService : Service() { if (mNotificationManager == null) mNotificationManager = getSystemService( NOTIFICATION_SERVICE ) as NotificationManager? - NotificationChannels.ensureChannelsCreated(this) + NotificationChannels.ensureMonitoringChannelsCreated(this) } override fun onCreate() { @@ -529,7 +529,7 @@ class BatteryInfoService : Service() { setUpChannels() currentWorker.execute { if (!destroyed) runCatching { - NotificationChannels.syncAlarmChannels(applicationContext) + NotificationChannels.ensureChannelsCreated(applicationContext) }.onFailure { Log.w(LOG_TAG, "Could not synchronize alarm channels", it) } } @@ -668,7 +668,7 @@ class BatteryInfoService : Service() { } private fun stopAcquisition() { - destroyed = true + synchronized(this) { destroyed = true } PrivilegedAccess.setEnabled(false) mHandler.removeCallbacks(currentTick) currentAcquisition.close() @@ -1184,7 +1184,16 @@ class BatteryInfoService : Service() { ) else completeBatteryUpdate( pending, fields, voltageSource, times, remainingCharge - ) { alarmSnapshot.takeIf { settingsGeneration == alarmSettingsGeneration } } + ) { + if (settingsGeneration == alarmSettingsGeneration) alarmSnapshot + else { + Log.i( + LOG_TAG, + "Skipping alarm evaluation because settings changed during acquisition" + ) + null + } + } } } catch (error: Exception) { Log.e(LOG_TAG, "Could not acquire battery readings", error) @@ -2024,6 +2033,13 @@ class BatteryInfoService : Service() { } } + private data class TriggeredAlarm( + val type: String, + val title: String, + val thresholdId: Int? = null, + val triggerValue: Int? = null + ) + private fun handleAlarms( targetAlarmResult: TargetAlarmResult, resolvedTargets: ResolvedPredictionTargets, @@ -2039,19 +2055,9 @@ class BatteryInfoService : Service() { val dismissLowBatteryOnRecovery = settings.getBoolean( SettingsContract.KEY_DISMISS_LOW_BATTERY_ON_RECOVERY, false ) - AlarmNotifications.reconcileConfiguration( - this, snapshot, projection - ) { type, value, repeating -> - shouldDismissAlarmAfterBatteryUpdate( - type, - value, - repeating, - battery, - chargingTarget, - dischargingTarget, - dismissLowBatteryOnRecovery - ) - } + val recovery = AlarmRecoveryState( + battery, chargingTarget, dischargingTarget, dismissLowBatteryOnRecovery + ) val thresholds = projection.types.filter { it.definition.bounds != null }.flatMap { it.alarms } @@ -2071,35 +2077,32 @@ class BatteryInfoService : Service() { if (!spsEditor!!.commit()) Log.w(LOG_TAG, "Could not persist the alarm transition") } - if (fullyCharged) AlarmNotifications.post( - this, - snapshot, - CHAN_ID_A_CHARGED, - DisplayStrings.alarmFullyCharged, - currentInfoPendingIntent + val events = mutableListOf() + if (fullyCharged) events += TriggeredAlarm( + CHAN_ID_A_CHARGED, DisplayStrings.alarmFullyCharged ) if (targetAlarmResult.chargingLimitReached && enabled(CHAN_ID_A_CHARGING_LIMIT)) { - AlarmNotifications.post( - this, - snapshot, + events += TriggeredAlarm( CHAN_ID_A_CHARGING_LIMIT, getString(R.string.alarm_charging_target_reached, chargingTarget), - currentInfoPendingIntent, triggerValue = chargingTarget ) } if (targetAlarmResult.dischargingLimitReached && enabled(CHAN_ID_A_DISCHARGING_LIMIT)) { - AlarmNotifications.post( - this, - snapshot, + events += TriggeredAlarm( CHAN_ID_A_DISCHARGING_LIMIT, getString(R.string.alarm_discharging_target_reached, dischargingTarget), - currentInfoPendingIntent, triggerValue = dischargingTarget ) } for (alarm in crossed) { - if (alarm.type == CHAN_ID_A_CRISE && battery.plugged == BatteryInfo.PLUGGED_UNPLUGGED) continue + if (alarm.type == CHAN_ID_A_CRISE && battery.plugged == BatteryInfo.PLUGGED_UNPLUGGED) { + Log.i( + LOG_TAG, + "Skipping type=${alarm.type} thresholdId=${alarm.id} because power is disconnected" + ) + continue + } val threshold = checkNotNull(alarm.threshold) val title = when (alarm.type) { CHAN_ID_A_CDROP -> DisplayStrings.alarmChargeDrops + threshold + DisplayStrings.percentSymbol @@ -2114,16 +2117,52 @@ class BatteryInfoService : Service() { ) } } - AlarmNotifications.post( - this, snapshot, alarm.type, title, currentInfoPendingIntent, alarm.id, threshold - ) + events += TriggeredAlarm(alarm.type, title, alarm.id, threshold) } - if (healthFailed) AlarmNotifications.post( - this, - snapshot, + if (healthFailed) events += TriggeredAlarm( CHAN_ID_A_HFAIL, - DisplayStrings.alarmHealthFailure + DisplayStrings.healths[battery.health], - currentInfoPendingIntent + DisplayStrings.alarmHealthFailure + DisplayStrings.healths[battery.health] ) + val contentIntent = currentInfoPendingIntent + currentWorker.execute { + try { + if (events.isEmpty() && !AlarmNotifications.hasActiveAlarms(this)) return@execute + NotificationChannels.withCurrentAlarmSnapshot( + this, checkNotNull(alarms) + ) { current -> + if (destroyed) { + Log.i(LOG_TAG, "Skipping alarm processing because monitoring stopped") + return@withCurrentAlarmSnapshot + } + val currentProjection = projectAlarms(current.rules) + AlarmNotifications.reconcileConfiguration( + this, current, currentProjection, recovery::shouldDismiss + ) + for ((type, title, thresholdId, triggerValue) in events) { + synchronized(this) { + if (destroyed) { + Log.i( + LOG_TAG, + "Skipping type=$type thresholdId=$thresholdId because monitoring stopped" + ) + return@withCurrentAlarmSnapshot + } + AlarmNotifications.post( + this, + current, + type, + title, + contentIntent, + thresholdId, + triggerValue, + currentProjection + ) + } + } + } + } catch (error: Exception) { + Log.e(LOG_TAG, "Could not process alarm notifications", error) + } + } } } diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluator.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluator.kt index c3efeb05..263d231f 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluator.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluator.kt @@ -49,25 +49,27 @@ internal class ThresholdAlarmEvaluator { } } -internal fun shouldDismissAlarmAfterBatteryUpdate( - type: String, - value: Int?, - repeating: Boolean, +internal class AlarmRecoveryState( battery: BatteryInfo, - chargingTarget: Int, - dischargingTarget: Int, - dismissLowBatteryOnRecovery: Boolean -): Boolean { - val plugged = battery.plugged != BatteryInfo.PLUGGED_UNPLUGGED - return when (type) { - "fully_charged" -> !plugged || (repeating && battery.status != BatteryInfo.STATUS_FULLY_CHARGED) - "charge_rises" -> !plugged || (repeating && value != null && battery.percent < value) - "charge_drops" -> dismissLowBatteryOnRecovery && value != null && value in 0..100 && battery.percent > value - "charging_limit_met" -> !plugged || value != chargingTarget || (repeating && battery.percent < chargingTarget) - "discharging_limit_met" -> plugged || value != dischargingTarget || ((repeating || dismissLowBatteryOnRecovery) && battery.percent > dischargingTarget) - "temp_rises" -> repeating && value != null && battery.temperature < value - "temp_drops" -> repeating && value != null && battery.temperature > value - "health_failure" -> repeating && battery.health == BatteryInfo.HEALTH_GOOD + private val chargingTarget: Int, + private val dischargingTarget: Int, + private val dismissLowBatteryOnRecovery: Boolean +) { + private val plugged = battery.plugged != BatteryInfo.PLUGGED_UNPLUGGED + private val status = battery.status + private val percent = battery.percent + private val temperature = battery.temperature + private val health = battery.health + + fun shouldDismiss(type: String, value: Int?, repeating: Boolean): Boolean = when (type) { + "fully_charged" -> !plugged || (repeating && status != BatteryInfo.STATUS_FULLY_CHARGED) + "charge_rises" -> !plugged || (repeating && value != null && percent < value) + "charge_drops" -> dismissLowBatteryOnRecovery && value != null && value in 0..100 && percent > value + "charging_limit_met" -> !plugged || value != chargingTarget || (repeating && percent < chargingTarget) + "discharging_limit_met" -> plugged || value != dischargingTarget || ((repeating || dismissLowBatteryOnRecovery) && percent > dischargingTarget) + "temp_rises" -> repeating && value != null && temperature < value + "temp_drops" -> repeating && value != null && temperature > value + "health_failure" -> repeating && health == BatteryInfo.HEALTH_GOOD else -> false } } diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt index 902d6a16..78597fc6 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt @@ -7,7 +7,9 @@ import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.graphics.drawable.Icon +import android.media.AudioManager import android.net.Uri +import android.os.Build import android.os.Bundle import android.service.notification.StatusBarNotification import android.util.Log @@ -15,10 +17,14 @@ import codes.swistak.batterymonitor.R import codes.swistak.batterymonitor.alarms.AlarmPlayback import codes.swistak.batterymonitor.alarms.AlarmProjection import codes.swistak.batterymonitor.alarms.AlarmSnapshot +import codes.swistak.batterymonitor.alarms.AlarmVolumeCategory import codes.swistak.batterymonitor.alarms.projectAlarms import java.util.UUID + internal object AlarmNotifications { + private const val LOG_TAG = "AlarmNotifications" + private const val ID = 7 private const val TAG_PREFIX = "alarm:" private const val ACTION_STOP = "codes.swistak.batterymonitor.action.STOP_ALARM" @@ -36,6 +42,7 @@ internal object AlarmNotifications { private fun Notification.isRepeating(): Boolean = flags and Notification.FLAG_INSISTENT != 0 + @Synchronized fun post( context: Context, snapshot: AlarmSnapshot, @@ -43,21 +50,58 @@ internal object AlarmNotifications { title: String, contentIntent: PendingIntent?, thresholdId: Int? = null, - triggerValue: Int? = null + triggerValue: Int? = null, + projection: AlarmProjection? = null ) { val manager = context.getSystemService(NotificationManager::class.java) val configuration = snapshot.effective(type, thresholdId) val channelId = NotificationChannels.alarmChannelId(type, configuration) - if (!manager.areNotificationsEnabled()) return - val channel = manager.getNotificationChannel(channelId) ?: return - if (channel.importance == NotificationManager.IMPORTANCE_NONE) return + val stream = configuration.sound.volumeCategory + val category = Notification.CATEGORY_ALARM.takeIf { stream == AlarmVolumeCategory.ALARMS } + val eventDetails = + "type=$type thresholdId=$thresholdId channel=$channelId " + "requestedStream=$stream category=$category playback=${configuration.sound.playback}" + + val rows = (projection ?: projectAlarms(snapshot.rules)).types.firstOrNull { + it.definition.type == type + } + val rule = rows?.alarms?.firstOrNull { alarm -> + if (rows.definition.bounds == null) thresholdId == null else alarm.id == thresholdId + } + if (rule == null || !rule.enabled || (thresholdId != null && rule.threshold != triggerValue)) { + Log.i(LOG_TAG, "Skipped alarm: rule removed, disabled or edited; $eventDetails") + return + } + + val channel = manager.getNotificationChannel(channelId) + val groupBlocked = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && channel?.group?.let { + manager.getNotificationChannelGroup(it)?.isBlocked + } == true + val details = + "$eventDetails ${NotificationChannels.registeredAlarmDetails(channel)} " + "groupBlocked=$groupBlocked ${ + audioState( + context, + manager, + stream + ) + }" + val skipReason = when { + !manager.areNotificationsEnabled() -> "app notifications disabled" + channel == null -> "channel missing" + channel.importance == NotificationManager.IMPORTANCE_NONE -> "channel blocked" + groupBlocked -> "channel group blocked" + else -> null + } + if (skipReason != null) { + Log.i(LOG_TAG, "Skipped alarm: $skipReason; $details") + return + } val tag = tag(type, thresholdId) val repeat = configuration.sound.playback == AlarmPlayback.REPEAT val builder = Notification.Builder(context, channelId).setSmallIcon(R.drawable.stat_notify_alarm) .setContentTitle(title).setVisibility(Notification.VISIBILITY_PUBLIC) - .setAutoCancel(true).setContentIntent(contentIntent) + .setAutoCancel(true).setContentIntent(contentIntent).setCategory(category) val extras = Bundle().apply { if (triggerValue != null) putInt(EXTRA_TRIGGER_VALUE, triggerValue) } @@ -66,8 +110,7 @@ internal object AlarmNotifications { extras.putString(EXTRA_EVENT, event) val stopIntent = Intent(context, AlarmStopReceiver::class.java).setAction(ACTION_STOP).setData( - Uri.Builder().scheme("battery-alarm").appendPath(tag).appendPath(event) - .build() + Uri.Builder().scheme("battery-alarm").appendPath(tag).appendPath(event).build() ) val stop = PendingIntent.getBroadcast( context, 0, stopIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT @@ -84,13 +127,30 @@ internal object AlarmNotifications { if (repeat) notification.flags = notification.flags or Notification.FLAG_INSISTENT try { manager.notify(tag, ID, notification) - } catch (error: SecurityException) { - Log.w( - "AlarmNotifications", "Alarm notification permission changed before delivery", error - ) + Log.i(LOG_TAG, "Alarm submitted to NotificationManager: $details") + } catch (error: RuntimeException) { + Log.w(LOG_TAG, "Alarm submission failed (${error.javaClass.simpleName}): $details") } } + private fun audioState( + context: Context, manager: NotificationManager, category: AlarmVolumeCategory + ): String { + val stream = when (category) { + AlarmVolumeCategory.NOTIFICATIONS -> AudioManager.STREAM_NOTIFICATION + AlarmVolumeCategory.ALARMS -> AudioManager.STREAM_ALARM + AlarmVolumeCategory.MEDIA -> AudioManager.STREAM_MUSIC + } + val audio = context.getSystemService(AudioManager::class.java) + val volume = runCatching { audio.getStreamVolume(stream) }.getOrNull() + val ringer = runCatching { audio.ringerMode }.getOrNull() + val filter = runCatching { manager.currentInterruptionFilter }.getOrNull() + return "requestedStreamVolume=$volume ringerMode=$ringer interruptionFilter=$filter" + } + + fun hasActiveAlarms(context: Context): Boolean = + context.getSystemService(NotificationManager::class.java).activeNotifications.any { it.isAlarm() } + fun reconcileConfiguration( context: Context, snapshot: AlarmSnapshot, @@ -115,26 +175,47 @@ internal object AlarmNotifications { val repeating = notification.isRepeating() val thresholdId = if (alarm?.thresholdKey != null) alarm.id else null val config = alarm?.let { snapshot.effective(it.type, thresholdId) } - if (alarm == null || config == null || (thresholdId != null && alarm.threshold != value) || NotificationChannels.alarmChannelId( + val reason = when { + alarm == null || config == null -> "rule disabled or removed" + thresholdId != null && alarm.threshold != value -> "threshold changed" + NotificationChannels.alarmChannelId( alarm.type, config - ) != notification.channelId || (config.sound.playback == AlarmPlayback.REPEAT) != repeating || recovered( - alarm.type, - value, - repeating - ) - ) manager.cancel(posted.tag, posted.id) + ) != notification.channelId -> "channel changed" + + (config.sound.playback == AlarmPlayback.REPEAT) != repeating -> "playback mode changed" + recovered(alarm.type, value, repeating) -> "battery condition recovered" + else -> continue + } + manager.cancel(posted.tag, posted.id) + Log.i( + LOG_TAG, + "Cancelled alarm tag=${posted.tag} channel=${notification.channelId} reason=$reason" + ) } } + @Synchronized fun stop(context: Context, intent: Intent) { - val paths = intent.data?.pathSegments ?: return - if (intent.action != ACTION_STOP || paths.size != 2 || !paths[0].startsWith(TAG_PREFIX)) return + val paths = intent.data?.pathSegments.orEmpty() + if (intent.action != ACTION_STOP || paths.size != 2 || !paths[0].startsWith(TAG_PREFIX)) { + Log.w(LOG_TAG, "Ignored malformed alarm stop action") + return + } val (tag, event) = paths val manager = context.getSystemService(NotificationManager::class.java) - if (manager.activeNotifications.any { - it.id == ID && it.tag == tag && it.notification.extras.getString(EXTRA_EVENT) == event - }) manager.cancel(tag, ID) + val posted = manager.activeNotifications.firstOrNull { + it.id == ID && it.tag == tag && it.notification.extras.getString(EXTRA_EVENT) == event + } + if (posted == null) { + Log.i(LOG_TAG, "Ignored stop action for an alarm event that is no longer active") + return + } + manager.cancel(tag, ID) + Log.i( + LOG_TAG, + "Cancelled alarm tag=$tag channel=${posted.notification.channelId} reason=user stopped" + ) } } diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt index ed99176f..ef79db97 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt @@ -94,7 +94,9 @@ internal object NotificationChannels { else snapshot.custom[alarmId] ?: return@withAlarmChannelLock null val id = alarmChannelId(type, configuration) syncAlarmGroup(context, manager, createIfMissing = true) - if (id == type) ensureChannel(context, manager, alarmDefinitions.getValue(type)) + if (id == type) ensureChannel( + context, manager, alarmDefinitions.getValue(type), sound = configuration.sound + ) syncManagedAlarms(context, manager, snapshot, createMissing = true) id.takeIf { manager.getNotificationChannel(it) != null } } @@ -117,29 +119,61 @@ internal object NotificationChannels { val manager = context.getSystemService(NotificationManager::class.java) val fallback = snapshot.effective(type) val currentId = alarmChannelId(type, current ?: fallback) - val source = manager.getNotificationChannel(currentId) + val registered = manager.getNotificationChannel(currentId) + val existing = if (registered == null && (current ?: fallback).channelId != null) { + val parent = manager.getNotificationChannel(alarmChannelId(type, fallback)) + ?: manager.getNotificationChannel(type) + syncAlarmGroup(context, manager, createIfMissing = true) + createAlarmChannel( + context, + manager, + definition, + currentId, + if (current == null) null else alarm?.thresholdKey, + (current ?: fallback).sound, + parent, + recreating = true + ) + } else registered val createCustom = alarm != null && current == null - val changeCategory = sound.volumeCategory != (current ?: fallback).sound.volumeCategory - check(!changeCategory || createCustom || source == null || replacementConfirmed) - val id = if (createCustom || changeCategory) newChannelId() else current?.channelId - val staged = if (createCustom || changeCategory) id else null + val changeChannel = shouldChangeAlarmChannel((current ?: fallback).sound, sound, existing) + check(!changeChannel || createCustom || registered == null || replacementConfirmed) + val staged = if (createCustom || changeChannel) newChannelId() else null + val id = staged ?: current?.channelId try { if (staged != null) { syncAlarmGroup(context, manager, createIfMissing = true) createAlarmChannel( - context, manager, definition, staged, alarm?.thresholdKey, sound, source + context, manager, definition, staged, alarm?.thresholdKey, sound, existing ) } val configuration = AlarmConfiguration(sound, id) if (alarm == null) database.saveSharedSettings(type, expected, configuration) else database.saveCustomSettings(alarm, expected, configuration) } catch (failure: Exception) { - staged?.let(manager::deleteNotificationChannel) + Log.w( + "NotificationChannels", + "Alarm settings save failed type=$type thresholdId=${alarm?.id} " + "stream=${sound.volumeCategory} previous=$currentId staged=$staged error=${failure.javaClass.simpleName}" + ) + staged?.let { deleteStagedAlarmChannel(manager, it) } throw failure } reconcileSavedAlarms(context, manager, database) } + private fun shouldChangeAlarmChannel( + previous: AlarmSoundSettings, requested: AlarmSoundSettings, channel: NotificationChannel? + ): Boolean = + previous.volumeCategory != requested.volumeCategory && channel?.audioAttributes != alarmAudioAttributes( + requested.volumeCategory + ) + + private fun deleteStagedAlarmChannel(manager: NotificationManager, id: String) { + runCatching { manager.deleteNotificationChannel(id) }.onFailure { + Log.w("NotificationChannels", "Could not remove unused staged alarm channel=$id", it) + } + } + fun alarmRestoreMayReplaceChannels( context: Context, database: AlarmDatabase, @@ -163,16 +197,43 @@ internal object NotificationChannels { val current = database.getSnapshot() val manager = context.getSystemService(NotificationManager::class.java) if (!allowChannelChanges && restoreMayReplaceChannels(manager, current, shared, custom)) { + Log.i( + "NotificationChannels", + "Alarm restore requires confirmation to change registered channels" + ) return@withAlarmChannelLock false } val oldCustom = customByThreshold(current) val staged = mutableListOf() - fun stage( + fun restoreChannel( definition: Definition, key: AlarmThresholdKey?, + previous: AlarmConfiguration?, sound: AlarmSoundSettings, - sourceId: String - ): String { + fallbackId: String + ): String? { + val previousId = previous?.channelId ?: definition.id.takeIf { key == null } + val registered = + previousId?.let(manager::getNotificationChannel) ?: previous?.channelId?.let { id -> + staged += id + syncAlarmGroup(context, manager, createIfMissing = true) + createAlarmChannel( + context, + manager, + definition, + id, + key, + previous.sound, + manager.getNotificationChannel(fallbackId), + recreating = true + ) + } + if (previous != null && previousId != null && !shouldChangeAlarmChannel( + previous.sound, sound, registered + ) + ) { + return previous.channelId + } val id = newChannelId() staged += id syncAlarmGroup(context, manager, createIfMissing = true) @@ -183,7 +244,7 @@ internal object NotificationChannels { id, key, sound, - manager.getNotificationChannel(sourceId) + registered ?: manager.getNotificationChannel(fallbackId) ) return id } @@ -192,23 +253,24 @@ internal object NotificationChannels { try { val sharedIds = buildMap { for ((type, definition) in alarmDefinitions) { - val previous = current.effective(type) - val sound = shared[type] ?: AlarmSoundSettings() - if (sound.volumeCategory != previous.sound.volumeCategory) { - put(type, stage(definition, null, sound, alarmChannelId(type, previous))) - } + restoreChannel( + definition, + null, + current.effective(type), + shared[type] ?: AlarmSoundSettings(), + type + )?.let { put(type, it) } } } val customIds = buildMap { for ((key, sound) in custom) { - val previous = oldCustom[key] - if (previous?.channelId == null || previous.sound.volumeCategory != sound.volumeCategory) { - val sourceId = previous?.channelId ?: sharedIds[key.type] ?: alarmChannelId( - key.type, - current.effective(key.type) - ) - put(key, stage(alarmDefinitions.getValue(key.type), key, sound, sourceId)) - } + restoreChannel( + alarmDefinitions.getValue(key.type), + key, + oldCustom[key], + sound, + sharedIds[key.type] ?: key.type + )?.let { put(key, it) } } } committed = database.replaceAllAlarms( @@ -219,19 +281,54 @@ internal object NotificationChannels { expected = current ) } finally { - if (!committed) staged.forEach(manager::deleteNotificationChannel) + if (!committed) { + Log.w( + "NotificationChannels", + "Alarm restore did not commit; discarding ${staged.size} staged channels" + ) + staged.forEach { deleteStagedAlarmChannel(manager, it) } + } } if (committed) reconcileSavedAlarms(context, manager, database) committed } - fun syncAlarmChannels(context: Context) = withAlarmChannelLock(context) { - val manager = context.getSystemService(NotificationManager::class.java) - val snapshot = readAlarmSnapshot(context) - syncManagedAlarms(context, manager, snapshot, createMissing = true) - AlarmNotifications.reconcileConfiguration(context, snapshot) + fun withCurrentAlarmSnapshot( + context: Context, database: AlarmDatabase, operation: (AlarmSnapshot) -> Unit + ) = withAlarmChannelLock(context) { operation(database.getSnapshot()) } + + fun mutateAlarmRules( + context: Context, database: AlarmDatabase, operation: (AlarmDatabase) -> Unit + ): Boolean = withAlarmChannelLock(context) { + operation(database) + reconcileSavedAlarms( + context, context.getSystemService(NotificationManager::class.java), database + ) } + fun syncAlarmChannels(context: Context, ensureOriginals: Boolean = false) = + withAlarmChannelLock(context) { + val manager = context.getSystemService(NotificationManager::class.java) + val snapshot = readAlarmSnapshot(context) + if (ensureOriginals) { + syncAlarmGroup(context, manager, createIfMissing = true) + for ((type, definition) in alarmDefinitions) { + val active = snapshot.effective(type) + if (alarmChannelId(type, active) != type) continue + try { + ensureChannel(context, manager, definition, sound = active.sound) + } catch (failure: RuntimeException) { + Log.w( + "NotificationChannels", + "Could not initialize alarm channel=$type error=${failure.javaClass.simpleName}" + ) + } + } + } + AlarmNotifications.reconcileConfiguration(context, snapshot) + syncManagedAlarms(context, manager, snapshot, createMissing = true) + } + private fun readAlarmSnapshot(context: Context): AlarmSnapshot { val database = AlarmDatabase(context) return try { @@ -243,17 +340,16 @@ internal object NotificationChannels { private fun reconcileSavedAlarms( context: Context, manager: NotificationManager, database: AlarmDatabase - ) { - // A cleanup error must not report a failed save after the database commits. - runCatching { + ): Boolean { + return runCatching { val snapshot = database.getSnapshot() - syncManagedAlarms(context, manager, snapshot, createMissing = true) AlarmNotifications.reconcileConfiguration(context, snapshot) + syncManagedAlarms(context, manager, snapshot, createMissing = true) }.onFailure { Log.w( "NotificationChannels", "Could not reconcile saved alarm channels", it ) - } + }.isSuccess } private fun restoreMayReplaceChannels( @@ -263,19 +359,14 @@ internal object NotificationChannels { custom: Map ): Boolean = alarmDefinitions.keys.any { type -> val previous = current.effective(type) - previous.sound.volumeCategory != (shared[type] - ?: AlarmSoundSettings()).volumeCategory && manager.getNotificationChannel( - alarmChannelId( - type, - previous - ) - ) != null + val channel = manager.getNotificationChannel(alarmChannelId(type, previous)) + channel != null && shouldChangeAlarmChannel( + previous.sound, shared[type] ?: AlarmSoundSettings(), channel + ) } || customByThreshold(current).any { (key, previous) -> - previous.sound.volumeCategory != custom[key]?.volumeCategory && previous.channelId?.let { - manager.getNotificationChannel( - it - ) - } != null + val channel = previous.channelId?.let(manager::getNotificationChannel) ?: return@any false + val requested = custom[key] + requested == null || shouldChangeAlarmChannel(previous.sound, requested, channel) } private fun customByThreshold(snapshot: AlarmSnapshot): Map = @@ -314,7 +405,10 @@ internal object NotificationChannels { id, key, configuration.sound, - manager.getNotificationChannel(sourceId) + manager.getNotificationChannel(sourceId) ?: manager.getNotificationChannel( + definition.id + ), + recreating = true ) } } @@ -324,7 +418,7 @@ internal object NotificationChannels { val original = manager.getNotificationChannel(type) ?: continue val name = context.getString(definition.name) refreshName( - manager, original, if (shared.channelId == null) name + manager, original, if (alarmChannelId(type, shared) == type) name else context.getString(R.string.alarm_inactive_channel_name, name) ) } @@ -339,13 +433,14 @@ internal object NotificationChannels { } for (channel in manager.notificationChannels) { if (channel.id.startsWith(MANAGED_ALARM_PREFIX) && channel.id !in retained) { + Log.i("NotificationChannels", "Removing obsolete alarm channel=${channel.id}") manager.deleteNotificationChannel(channel.id) } } } private fun newChannelId(): String = MANAGED_ALARM_PREFIX + UUID.randomUUID().toString() - + @Synchronized private fun withAlarmChannelLock(context: Context, operation: () -> T): T = RandomAccessFile( @@ -379,58 +474,89 @@ internal object NotificationChannels { id: String, key: AlarmThresholdKey?, settings: AlarmSoundSettings, - source: NotificationChannel? - ) { - val channel = NotificationChannel( - id, - alarmName(context, definition, key), - source?.importance ?: NotificationManager.IMPORTANCE_HIGH - ).apply { - group = CHAN_GROUP_ID_ALARMS - if (source == null) { - setDefaultAlarmOptions(this, settings.volumeCategory) - lockscreenVisibility = Notification.VISIBILITY_PUBLIC - } else { - description = source.description - val audio = source.audioAttributes?.let { AudioAttributes.Builder(it) } - ?: AudioAttributes.Builder() - setSound(source.sound, audio.setUsage(settings.volumeCategory.usage).build()) - enableLights(source.shouldShowLights()) - lightColor = source.lightColor - if (Build.VERSION.SDK_INT >= 35 && source.vibrationEffect != null) { - vibrationEffect = source.vibrationEffect - } else vibrationPattern = source.vibrationPattern - enableVibration(source.shouldVibrate()) - setShowBadge(source.canShowBadge()) - lockscreenVisibility = source.lockscreenVisibility - if (manager.isNotificationPolicyAccessGranted) setBypassDnd(source.canBypassDnd()) + source: NotificationChannel?, + recreating: Boolean = false + ): NotificationChannel { + val importance = source?.importance ?: NotificationManager.IMPORTANCE_HIGH + val sound = if (source != null) source.sound + else RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) + val attributes = alarmAudioAttributes(settings.volumeCategory) + val channel = + NotificationChannel(id, alarmName(context, definition, key), importance).apply { + group = CHAN_GROUP_ID_ALARMS + setSound(sound, attributes) + if (source == null) { + enableLights(true) + lightColor = -0xcc4a1b + vibrationPattern = longArrayOf(0, 500, 500, 500, 500, 1000, 1000, 1000, 1000) + enableVibration(true) + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + } else { + description = source.description + enableLights(source.shouldShowLights()) + lightColor = source.lightColor + if (Build.VERSION.SDK_INT >= 35 && source.vibrationEffect != null) { + vibrationEffect = source.vibrationEffect + } else vibrationPattern = source.vibrationPattern + enableVibration(source.shouldVibrate()) + setShowBadge(source.canShowBadge()) + lockscreenVisibility = source.lockscreenVisibility + if (manager.isNotificationPolicyAccessGranted) setBypassDnd(source.canBypassDnd()) + } } + val request = + "type=${definition.id} threshold=${key?.threshold} channel=$id " + "source=${source?.id} stream=${settings.volumeCategory} playback=${settings.playback}" + val registered = try { + manager.createNotificationChannel(channel) + checkNotNull(manager.getNotificationChannel(id)) { + "Android did not register the alarm channel" + } + } catch (failure: RuntimeException) { + if (recreating) deleteStagedAlarmChannel(manager, id) + Log.w( + "NotificationChannels", + "Alarm channel registration failed $request error=${failure.javaClass.simpleName}" + ) + throw failure } - manager.createNotificationChannel(channel) - checkNotNull(manager.getNotificationChannel(id)) { "Android did not register the alarm channel" } + val details = "$request ${registeredAlarmDetails(registered)}" + val soundMatches = registered.sound == sound + if (registered.audioAttributes?.usage != attributes.usage || registered.audioAttributes?.contentType != attributes.contentType || registered.importance != importance || !soundMatches || (source != null && registered.canBypassDnd() != source.canBypassDnd())) { + Log.w( + "NotificationChannels", + "Android adjusted alarm channel settings $details requestedImportance=$importance " + "soundMatches=$soundMatches bypassDnd=${registered.canBypassDnd()}" + ) + } else { + Log.i("NotificationChannels", "Registered alarm channel $details") + } + val rejection = when { + importance == NotificationManager.IMPORTANCE_NONE && registered.importance != NotificationManager.IMPORTANCE_NONE -> "Android re-enabled a blocked alarm channel" + + sound == null && registered.sound != null -> "Android enabled sound on a silent alarm channel" + !recreating && !soundMatches -> "Android changed the selected alarm sound" + else -> null + } + if (rejection != null) { + if (recreating) deleteStagedAlarmChannel(manager, id) + error(rejection) + } + return registered } - private val AlarmVolumeCategory.usage: Int - get() = when (this) { + private fun alarmAudioAttributes(category: AlarmVolumeCategory): AudioAttributes { + val usage = when (category) { AlarmVolumeCategory.NOTIFICATIONS -> AudioAttributes.USAGE_NOTIFICATION AlarmVolumeCategory.ALARMS -> AudioAttributes.USAGE_ALARM AlarmVolumeCategory.MEDIA -> AudioAttributes.USAGE_MEDIA } - - private fun setDefaultAlarmOptions( - channel: NotificationChannel, category: AlarmVolumeCategory - ) { - channel.setSound( - RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), - AudioAttributes.Builder().setUsage(category.usage).build() - ) - channel.enableLights(true) - channel.lightColor = -0xcc4a1b - channel.enableVibration(true) - channel.vibrationPattern = longArrayOf(0, 500, 500, 500, 500, 1000, 1000, 1000, 1000) - channel.group = CHAN_GROUP_ID_ALARMS + return AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(usage).build() } + fun registeredAlarmDetails(channel: NotificationChannel?): String = + if (channel == null) "registered=false" + else "usage=${channel.audioAttributes?.usage} contentType=${channel.audioAttributes?.contentType} " + "importance=${channel.importance} blocked=${channel.importance == NotificationManager.IMPORTANCE_NONE} " + "hasSound=${channel.sound != null}" + fun ensureForegroundChannelCreated(context: Context) { ensureChannel( context, @@ -441,9 +567,15 @@ internal object NotificationChannels { } fun ensureChannelsCreated(context: Context) { + ensureMonitoringChannelsCreated(context) + syncAlarmChannels(context, ensureOriginals = true) + } + + fun ensureMonitoringChannelsCreated(context: Context) { val manager = context.getSystemService(NotificationManager::class.java) - syncAlarmGroup(context, manager, createIfMissing = true) - for (definition in definitions) ensureChannel(context, manager, definition) + for (definition in definitions) if (!definition.alarm) ensureChannel( + context, manager, definition + ) } fun refreshExistingChannelNames( @@ -473,7 +605,8 @@ internal object NotificationChannels { context: Context, manager: NotificationManager, definition: Definition, - minimal: Boolean = false + minimal: Boolean = false, + sound: AlarmSoundSettings = AlarmSoundSettings() ) { val existing = manager.getNotificationChannel(definition.id) if (existing != null) { @@ -481,19 +614,19 @@ internal object NotificationChannels { if (!definition.alarm) refreshName(context, manager, definition, existing) return } - val channel = NotificationChannel( - definition.id, - context.getString(definition.name), - if (definition.alarm) NotificationManager.IMPORTANCE_HIGH else NotificationManager.IMPORTANCE_LOW - ) if (definition.alarm) { - setDefaultAlarmOptions(channel, AlarmVolumeCategory.NOTIFICATIONS) - } else { - channel.setSound(null, null) - channel.enableLights(false) - channel.enableVibration(false) - channel.setShowBadge(false) + createAlarmChannel( + context, manager, definition, definition.id, null, sound, null, recreating = true + ) + return } + val channel = NotificationChannel( + definition.id, context.getString(definition.name), NotificationManager.IMPORTANCE_LOW + ) + channel.setSound(null, null) + channel.enableLights(false) + channel.enableVibration(false) + channel.setShowBadge(false) // Preserve the original minimal channel before entering foreground mode. if (!minimal) channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC manager.createNotificationChannel(channel) diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt index a98bd309..22346dc0 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt @@ -290,7 +290,7 @@ internal class AlarmsViewModel( sound: AlarmSoundSettings, replacementConfirmed: Boolean, onSaved: () -> Unit - ) = mutate(onSuccess = onSaved, syncChannels = false) { database -> + ) = mutateAndSync(onSaved) { database -> NotificationChannels.saveAlarmSettings( getApplication(), database, type, alarm, expected, sound, replacementConfirmed ) @@ -321,20 +321,20 @@ internal class AlarmsViewModel( } } - private fun mutate( - onSuccess: () -> Unit, syncChannels: Boolean = true, operation: (AlarmDatabase) -> Unit + private fun mutate(onSuccess: () -> Unit, operation: (AlarmDatabase) -> Unit) = + mutateAndSync(onSuccess) { database -> + NotificationChannels.mutateAlarmRules(getApplication(), database, operation) + } + + private fun mutateAndSync( + onSuccess: () -> Unit, operation: (AlarmDatabase) -> Boolean ) { if (!state.value.canMutate) return refreshJob?.cancel() mutableState.update { it.copy(busy = true, error = null) } viewModelScope.launch { val result = withContext(Dispatchers.IO) { - runCatching { - withDatabase(operation) - !syncChannels || runCatching { - NotificationChannels.syncAlarmChannels(getApplication()) - }.isSuccess - } + runCatching { withDatabase(operation) } } result.fold(onSuccess = { channelsSynced -> mutableState.update { it.copy(busy = false) } diff --git a/app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt b/app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt new file mode 100644 index 00000000..750af85f --- /dev/null +++ b/app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt @@ -0,0 +1,184 @@ +package codes.swistak.batterymonitor.alarms.backup + +import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager +import android.media.AudioAttributes +import codes.swistak.batterymonitor.alarms.AlarmConfiguration +import codes.swistak.batterymonitor.alarms.AlarmDatabase +import codes.swistak.batterymonitor.alarms.AlarmSoundSettings +import codes.swistak.batterymonitor.alarms.AlarmVolumeCategory +import codes.swistak.batterymonitor.alarms.projectAlarms +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.shadow.api.Shadow +import org.robolectric.shadows.ShadowNotificationManager + +@RunWith(RobolectricTestRunner::class) +@Config( + sdk = [36], + application = Application::class, + shadows = [AlarmChannelRestoreTest.RejectingNotificationManager::class] +) +class AlarmChannelRestoreTest { + @Test + fun `restore reuses a local threshold channel that already has the requested attributes`() { + val context = RuntimeEnvironment.getApplication() + val database = AlarmDatabase(context) + val manager = context.getSystemService(NotificationManager::class.java) + val type = "charge_drops" + val id = "alarm_settings_existing" + try { + database.saveThreshold(type, "17", emptyList()) + val alarm = + projectAlarms(database.getAlarmRules()).types.single { it.definition.type == type }.alarms.single() + database.saveCustomSettings(alarm, null, AlarmConfiguration(AlarmSoundSettings(), id)) + val audio = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build() + manager.createNotificationChannel( + NotificationChannel(id, id, NotificationManager.IMPORTANCE_LOW).apply { + setSound( + null, audio + ) + }) + val backup = JSONObject( + """{ + "version":3, "alarms":[{"enabled":true,"type":"charge_drops","threshold":"17"}], + "customSettings":[{"type":"charge_drops","threshold":17,"volumeCategory":"ALARMS"}] + }""" + ) + val preview = AlarmBackup.parseImport(backup) + + assertFalse(AlarmBackup.mayReplaceChannels(context, preview)) + AlarmBackup.restore(context, database, preview) + + val settings = database.getSnapshot().custom.values.single() + assertEquals(id, settings.channelId) + assertEquals(AlarmVolumeCategory.ALARMS, settings.sound.volumeCategory) + assertEquals(listOf(id), manager.notificationChannels.map { it.id }) + } finally { + database.close() + context.deleteDatabase("alarms.db") + } + } + + @Test + fun `restore verifies missing retained channels before committing and respects the destination sound on retry`() { + val context = RuntimeEnvironment.getApplication() + val manager = context.getSystemService(NotificationManager::class.java) + val shadow = Shadow.extract(manager) + val type = "charge_drops" + val missingId = "alarm_settings_missing" + val database = AlarmDatabase(context) + try { + database.saveThreshold(type, "17", emptyList()) + val alarm = + projectAlarms(database.getAlarmRules()).types.single { it.definition.type == type }.alarms.single() + val settings = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.MEDIA) + database.saveCustomSettings( + alarm, null, AlarmConfiguration(settings, missingId) + ) + manager.createNotificationChannel( + NotificationChannel( + type, type, NotificationManager.IMPORTANCE_NONE + ).apply { setSound(null, null) }) + val before = database.getSnapshot() + val backup = """{ + "version":3, "alarms":[{"enabled":false,"type":"charge_drops","threshold":"17"}], + "sharedSettings":{"charge_drops":{"volumeCategory":"ALARMS"}}, + "customSettings":[{"type":"charge_drops","threshold":17,"volumeCategory":"MEDIA"}] + }""" + + shadow.rejectId = missingId + assertThrows(IllegalStateException::class.java) { + AlarmBackup.importFromJson(context, database, backup, allowChannelChanges = true) + } + assertEquals(before, database.getSnapshot()) + assertEquals(listOf(type), manager.notificationChannels.map { it.id }) + + shadow.rejectId = null + AlarmBackup.importFromJson( + context, + database, + backup.replace("MEDIA", "NOTIFICATIONS"), + allowChannelChanges = true + ) + val restored = database.getSnapshot() + assertFalse(restored.rules.single().enabled) + for ((configuration, usage) in listOf( + restored.shared.getValue(type) to AudioAttributes.USAGE_ALARM, + restored.custom.values.single() to AudioAttributes.USAGE_NOTIFICATION + )) { + val channel = + requireNotNull(manager.getNotificationChannel(requireNotNull(configuration.channelId))) + assertEquals(NotificationManager.IMPORTANCE_NONE, channel.importance) + assertNull(channel.sound) + assertEquals(usage, channel.audioAttributes.usage) + assertEquals( + AudioAttributes.CONTENT_TYPE_SONIFICATION, channel.audioAttributes.contentType + ) + } + } finally { + database.close() + context.deleteDatabase("alarms.db") + } + } + + @Test + fun `restoring a different stream copies the blocked silent channel recovered by Android`() { + val context = RuntimeEnvironment.getApplication() + val manager = context.getSystemService(NotificationManager::class.java) + val shadow = Shadow.extract(manager) + val type = "charge_drops" + val retainedId = "alarm_settings_previously_deleted" + val database = AlarmDatabase(context) + try { + database.saveSharedSettings(type, null, AlarmConfiguration(channelId = retainedId)) + // The original shared channel is audible. Android remembers different settings for the retained ID. + manager.createNotificationChannel( + NotificationChannel( + type, type, NotificationManager.IMPORTANCE_HIGH + ) + ) + shadow.rememberedChannel = NotificationChannel( + retainedId, type, NotificationManager.IMPORTANCE_NONE + ).apply { setSound(null, null) } + val backup = + """{"version":3,"alarms":[],"sharedSettings":{"charge_drops":{"volumeCategory":"ALARMS"}}}""" + AlarmBackup.importFromJson(context, database, backup, allowChannelChanges = true) + val id = requireNotNull(database.getSnapshot().shared.getValue(type).channelId) + val restored = requireNotNull(manager.getNotificationChannel(id)) + assertEquals(NotificationManager.IMPORTANCE_NONE, restored.importance) + assertNull(restored.sound) + assertEquals(AudioAttributes.USAGE_ALARM, restored.audioAttributes.usage) + assertNull(manager.getNotificationChannel(retainedId)) + } finally { + database.close() + context.deleteDatabase("alarms.db") + } + } + + @Implements(NotificationManager::class) + class RejectingNotificationManager : ShadowNotificationManager() { + var rejectId: String? = null + var rememberedChannel: NotificationChannel? = null + + @Implementation + public override fun createNotificationChannel(channel: NotificationChannel) { + if (channel.id != rejectId) { + super.createNotificationChannel(rememberedChannel?.takeIf { it.id == channel.id } + ?: channel) + } + } + } +} diff --git a/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluatorTest.kt b/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluatorTest.kt index 90ab6966..fce89123 100644 --- a/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluatorTest.kt +++ b/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/ThresholdAlarmEvaluatorTest.kt @@ -124,8 +124,8 @@ class ThresholdAlarmEvaluatorTest { fun `low battery dismissal requires opt in and recovery past each threshold`() { val battery = BatteryInfo().apply { percent = 16 } fun dismiss(threshold: Int, optIn: Boolean, repeating: Boolean = true) = - shouldDismissAlarmAfterBatteryUpdate( - "charge_drops", threshold, repeating, battery, 80, 10, optIn + AlarmRecoveryState(battery, 80, 10, optIn).shouldDismiss( + "charge_drops", threshold, repeating ) assertTrue(dismiss(15, true)) assertTrue(dismiss(15, true, repeating = false)) @@ -138,14 +138,8 @@ class ThresholdAlarmEvaluatorTest { fun `discharging target recovery dismisses repeating alarms and opted-in one-shot alarms`() { val battery = BatteryInfo().apply { plugged = BatteryInfo.PLUGGED_UNPLUGGED } fun dismiss(optIn: Boolean, repeating: Boolean = false) = - shouldDismissAlarmAfterBatteryUpdate( - type = "discharging_limit_met", - value = 20, - repeating = repeating, - battery = battery, - chargingTarget = 80, - dischargingTarget = 20, - dismissLowBatteryOnRecovery = optIn + AlarmRecoveryState(battery, 80, 20, optIn).shouldDismiss( + "discharging_limit_met", 20, repeating ) battery.percent = 19 @@ -168,9 +162,7 @@ class ThresholdAlarmEvaluatorTest { } fun dismiss(type: String, triggerValue: Int? = null, repeating: Boolean = true) = - shouldDismissAlarmAfterBatteryUpdate( - type, triggerValue, repeating, battery, 80, 10, false - ) + AlarmRecoveryState(battery, 80, 10, false).shouldDismiss(type, triggerValue, repeating) assertTrue(dismiss("fully_charged")) assertTrue(dismiss("charge_rises", 80)) diff --git a/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt b/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt index 4e444eb7..d6af7921 100644 --- a/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt +++ b/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt @@ -28,6 +28,7 @@ import android.net.Uri import android.os.LocaleList import android.os.Parcel import codes.swistak.batterymonitor.R +import codes.swistak.batterymonitor.alarms.AlarmConfiguration import codes.swistak.batterymonitor.alarms.AlarmDatabase import codes.swistak.batterymonitor.alarms.AlarmPlayback import codes.swistak.batterymonitor.alarms.AlarmSoundSettings @@ -111,6 +112,9 @@ class NotificationChannelsTest { assertEquals( AudioAttributes.USAGE_NOTIFICATION, channel.audioAttributes.usage ) + assertEquals( + AudioAttributes.CONTENT_TYPE_SONIFICATION, channel.audioAttributes.contentType + ) assertTrue(channel.shouldShowLights()) assertEquals(-0xcc4a1b, channel.lightColor) assertTrue(channel.shouldVibrate()) @@ -319,14 +323,20 @@ class NotificationChannelsTest { NotificationChannels.CHAN_GROUP_ID_ALARMS, "Alarms" ) ) + @Suppress("UsePropertyAccessSyntax") shadow.setNotificationPolicyAccessGranted(true) val baseline = NotificationChannel(type, "Legacy", NotificationManager.IMPORTANCE_NONE).apply { group = NotificationChannels.CHAN_GROUP_ID_ALARMS setSound( Uri.parse("content://test/alarm-tone"), AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT) - .build() + .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) + .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED).build() ) + setBypassDnd(true) + enableLights(true) + lightColor = 0xffaabbcc.toInt() + lockscreenVisibility = Notification.VISIBILITY_SECRET vibrationPattern = longArrayOf(0, 240, 480) setShowBadge(false) } @@ -359,6 +369,14 @@ class NotificationChannelsTest { val mediaId = requireNotNull(replaced.channelId) val mediaChannel = manager.getNotificationChannel(mediaId) assertEquals(AudioAttributes.USAGE_MEDIA, mediaChannel.audioAttributes.usage) + assertEquals( + AudioAttributes.CONTENT_TYPE_SONIFICATION, mediaChannel.audioAttributes.contentType + ) + assertEquals(0, mediaChannel.audioAttributes.flags) + assertEquals(original.canBypassDnd(), mediaChannel.canBypassDnd()) + assertEquals(original.shouldShowLights(), mediaChannel.shouldShowLights()) + assertEquals(original.lightColor, mediaChannel.lightColor) + assertEquals(original.lockscreenVisibility, mediaChannel.lockscreenVisibility) assertEquals(original.importance, mediaChannel.importance) assertEquals(original.sound, mediaChannel.sound) assertEquals(original.shouldVibrate(), mediaChannel.shouldVibrate()) @@ -381,6 +399,280 @@ class NotificationChannelsTest { ) assertNull(manager.getNotificationChannel(mediaId)) assertTrue(manager.notificationChannels.any { it.id == type }) + val alarmChannel = manager.getNotificationChannel(alarmId) + assertEquals( + AudioAttributes.CONTENT_TYPE_SONIFICATION, alarmChannel.audioAttributes.contentType + ) + assertEquals(original.sound, alarmChannel.sound) + val before = database.getSnapshot().shared.getValue(type) + NotificationChannels.saveAlarmSettings( + context, + database, + type, + null, + before, + before.sound.copy(volumeCategory = AlarmVolumeCategory.NOTIFICATIONS), + true + ) + val activeId = + NotificationChannels.alarmChannelId(type, database.getSnapshot().effective(type)) + val active = manager.getNotificationChannel(activeId) + assertEquals(AudioAttributes.USAGE_NOTIFICATION, active.audioAttributes.usage) + assertEquals( + AudioAttributes.CONTENT_TYPE_SONIFICATION, active.audioAttributes.contentType + ) + assertEquals(original.sound, active.sound) + assertEquals(NotificationManager.IMPORTANCE_NONE, active.importance) + assertNull(manager.getNotificationChannel(alarmId)) + } + + @Test + fun `a missing default alarm channel can be retried without preventing the others from registering`() { + val skipped = NotificationChannels.CHAN_ID_A_CHARGED + shadow.interceptRegistration = { it.takeUnless { channel -> channel.id == skipped } } + NotificationChannels.ensureChannelsCreated(context) + assertEquals( + expectedNames.keys - skipped, manager.notificationChannels.map { it.id }.toSet() + ) + + shadow.interceptRegistration = { it } + NotificationChannels.ensureChannelsCreated(context) + assertEquals(expectedNames.keys, manager.notificationChannels.map { it.id }.toSet()) + } + + @Test + fun `recreating a missing original channel honors its saved stream`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CHARGED + val requested = + AlarmConfiguration(AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS)) + database.saveSharedSettings(type, null, requested) + + NotificationChannels.ensureChannelsCreated(context) + + val active = manager.getNotificationChannel(type) + assertEquals(AudioAttributes.USAGE_ALARM, active.audioAttributes.usage) + assertEquals( + AudioAttributes.CONTENT_TYPE_SONIFICATION, active.audioAttributes.contentType + ) + assertEquals(requested, database.getSnapshot().effective(type)) + } + + @Test + fun `stream preference can match an existing channel without replacing it`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CHARGED + val requested = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS) + manager.createNotificationChannel( + NotificationChannel(type, "Existing", NotificationManager.IMPORTANCE_NONE).apply { + val attributes = AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_ALARM).build() + setSound(null, attributes) + }) + NotificationChannels.saveAlarmSettings( + context, database, type, null, null, requested, false + ) + + val configuration = database.getSnapshot().effective(type) + assertEquals(requested, configuration.sound) + assertEquals(type, NotificationChannels.alarmChannelId(type, configuration)) + assertEquals(setOf(type), manager.notificationChannels.map { it.id }.toSet()) + assertEquals( + NotificationManager.IMPORTANCE_NONE, manager.getNotificationChannel(type).importance + ) + assertNull(manager.getNotificationChannel(type).sound) + } + + @Test + fun `startup keeps the active channel when the user configured a stream before starting monitoring`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CHARGED + val settings = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS) + NotificationChannels.saveAlarmSettings( + context, database, type, null, null, settings, false + ) + val activeId = + NotificationChannels.alarmChannelId(type, database.getSnapshot().effective(type)) + NotificationChannels.ensureChannelsCreated(context) + assertEquals( + AudioAttributes.USAGE_ALARM, + manager.getNotificationChannel(activeId).audioAttributes.usage + ) + assertEquals( + 1, manager.notificationChannels.count { it.id == activeId || it.id == type }) + } + + @Test + fun `notifications use the current shared and dedicated channel after a stream switch`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CDROP + val inheritedId = database.saveThreshold(type, "20", emptyList()) + val customId = database.saveThreshold(type, "40", emptyList()) + val custom = + projectAlarms(database.getAlarmRules()).types.single { it.definition.type == type }.alarms.single { it.id == customId } + NotificationChannels.ensureChannelsCreated(context) + NotificationChannels.saveAlarmSettings( + context, + database, + type, + null, + null, + AlarmSoundSettings(AlarmPlayback.REPEAT, AlarmVolumeCategory.ALARMS), + true + ) + NotificationChannels.saveAlarmSettings( + context, + database, + type, + custom, + null, + AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.MEDIA), + false + ) + + fun submit(thresholdId: Int, threshold: Int): Notification { + val expectedChannel = + requireNotNull(database.getSnapshot().effective(type, thresholdId).channelId) + NotificationChannels.withCurrentAlarmSnapshot(context, database) { latest -> + AlarmNotifications.post( + context, latest, type, "Battery", null, thresholdId, threshold + ) + } + return manager.activeNotifications.map { it.notification } + .single { it.channelId == expectedChannel } + } + + val sharedNotification = submit(inheritedId, 20) + assertEquals(Notification.CATEGORY_ALARM, sharedNotification.category) + assertTrue(sharedNotification.flags and Notification.FLAG_INSISTENT != 0) + val media = submit(customId, 40) + assertNotEquals(Notification.CATEGORY_ALARM, media.category) + assertFalse(media.flags and Notification.FLAG_INSISTENT != 0) + + val previous = database.getSnapshot().custom.getValue(customId) + NotificationChannels.saveAlarmSettings( + context, + database, + type, + custom, + previous, + previous.sound.copy(volumeCategory = AlarmVolumeCategory.NOTIFICATIONS), + true + ) + assertNull(manager.getNotificationChannel(media.channelId)) + val updated = submit(customId, 40) + assertNotEquals(media.channelId, updated.channelId) + assertNotEquals(Notification.CATEGORY_ALARM, updated.category) + assertEquals( + setOf(sharedNotification.channelId, updated.channelId), + manager.activeNotifications.map { it.notification.channelId }.toSet() + ) + + // A threshold crossing can already be queued when the user disables the rule. + manager.cancelAll() + database.setLogicalEnabled(type, custom.members, false) + NotificationChannels.withCurrentAlarmSnapshot(context, database) { latest -> + AlarmNotifications.post(context, latest, type, "Battery", null, customId, 40) + } + assertTrue(manager.activeNotifications.isEmpty()) + } + + @Test + fun `threshold stream switches keep intentional silence and playback edits reuse its channel`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CDROP + manager.createNotificationChannel( + NotificationChannel(type, "Silent", NotificationManager.IMPORTANCE_HIGH).apply { + setSound(null, null) + }) + database.saveThreshold(type, "23", emptyList()) + val alarm = + projectAlarms(database.getAlarmRules()).types.single { it.definition.type == type }.alarms.single() + NotificationChannels.saveAlarmSettings( + context, + database, + type, + alarm, + null, + AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS), + false + ) + val initial = database.getSnapshot().custom.getValue(alarm.id) + val initialId = requireNotNull(initial.channelId) + assertNull(manager.getNotificationChannel(initialId).sound) + + val registered = shadow.channelUpdates + for (playback in listOf(initial.sound.playback, AlarmPlayback.REPEAT)) { + val expected = database.getSnapshot().custom.getValue(alarm.id) + NotificationChannels.saveAlarmSettings( + context, + database, + type, + alarm, + expected, + expected.sound.copy(playback = playback), + false + ) + assertEquals(initialId, database.getSnapshot().custom.getValue(alarm.id).channelId) + assertEquals(registered, shadow.channelUpdates) + } + + val expected = database.getSnapshot().custom.getValue(alarm.id) + NotificationChannels.saveAlarmSettings( + context, + database, + type, + alarm, + expected, + expected.sound.copy(volumeCategory = AlarmVolumeCategory.MEDIA), + true + ) + val updatedId = + requireNotNull(database.getSnapshot().custom.getValue(alarm.id).channelId) + val updated = manager.getNotificationChannel(updatedId) + assertNull(updated.sound) + assertEquals(AudioAttributes.USAGE_MEDIA, updated.audioAttributes.usage) + assertNull(manager.getNotificationChannel(initialId)) + assertNull(manager.getNotificationChannel(type).sound) + } + + @Test + fun `failed registration keeps the original channel and rolls back a rejected replacement`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CDROP + val selectedTone = Uri.parse("content://test/selected-tone") + manager.createNotificationChannel( + NotificationChannel(type, "Blocked", NotificationManager.IMPORTANCE_NONE).apply { + setSound(selectedTone, Notification.AUDIO_ATTRIBUTES_DEFAULT) + }) + val requested = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS) + val before = database.getSnapshot() + for (register in listOf<(NotificationChannel) -> NotificationChannel?>( + { null }, + { it.apply { importance = NotificationManager.IMPORTANCE_HIGH } }, + { channel -> + channel.apply { + setSound( + RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), + audioAttributes + ) + } + })) { + shadow.interceptRegistration = register + assertThrows(IllegalStateException::class.java) { + NotificationChannels.saveAlarmSettings( + context, database, type, null, null, requested, true + ) + } + assertEquals(before, database.getSnapshot()) + assertEquals(setOf(type), manager.notificationChannels.map { it.id }.toSet()) + assertEquals( + NotificationManager.IMPORTANCE_NONE, + manager.getNotificationChannel(type).importance + ) + assertEquals(selectedTone, manager.getNotificationChannel(type).sound) + } } private fun withDatabase(test: (AlarmDatabase) -> Unit) { @@ -420,11 +712,12 @@ class NotificationChannelsTest { class CountingNotificationManager : ShadowNotificationManager() { var channelUpdates = 0 var groupUpdates = 0 + var interceptRegistration: (NotificationChannel) -> NotificationChannel? = { it } @Implementation public override fun createNotificationChannel(channel: NotificationChannel) { channelUpdates++ - super.createNotificationChannel(channel) + super.createNotificationChannel(interceptRegistration(channel) ?: return) } @Implementation From 1ee392cbdbb94a0e88126a6cb9900078af2d8a6f Mon Sep 17 00:00:00 2001 From: Tomasz Swistak Date: Sun, 29 Nov 2026 19:53:01 +0100 Subject: [PATCH 2/6] further enforce alarm change rules --- .../alarms/AlarmDatabaseInstrumentedTest.kt | 125 ++++++- .../dialogs/DialogEditingInstrumentedTest.kt | 80 +++- .../batterymonitor/app/BatteryInfoActivity.kt | 4 +- .../notifications/AlarmNotifications.kt | 7 +- .../notifications/NotificationChannels.kt | 347 ++++++++++++------ .../settings/SettingsFragment.kt | 32 +- .../ui/alarms/AlarmSettingsDialog.kt | 106 ++++-- .../batterymonitor/ui/alarms/AlarmsScreen.kt | 27 +- .../ui/alarms/AlarmsViewModel.kt | 112 ++++-- app/src/main/res/values-ar/strings.xml | 4 + app/src/main/res/values-cs/strings.xml | 4 + app/src/main/res/values-de/strings.xml | 4 + app/src/main/res/values-el/strings.xml | 4 + app/src/main/res/values-es/strings.xml | 4 + app/src/main/res/values-fa/strings.xml | 4 + app/src/main/res/values-fr/strings.xml | 4 + app/src/main/res/values-hi/strings.xml | 4 + app/src/main/res/values-hu/strings.xml | 4 + app/src/main/res/values-it/strings.xml | 4 + app/src/main/res/values-iw/strings.xml | 4 + app/src/main/res/values-ja/strings.xml | 4 + app/src/main/res/values-lt/strings.xml | 4 + app/src/main/res/values-nl/strings.xml | 4 + app/src/main/res/values-pl/strings.xml | 4 + app/src/main/res/values-pt-rBR/strings.xml | 4 + app/src/main/res/values-pt/strings.xml | 4 + app/src/main/res/values-ro/strings.xml | 4 + app/src/main/res/values-ru/strings.xml | 4 + app/src/main/res/values-sk/strings.xml | 4 + app/src/main/res/values-sl/strings.xml | 4 + app/src/main/res/values-sr/strings.xml | 4 + app/src/main/res/values-tr/strings.xml | 4 + app/src/main/res/values-zh-rCN/strings.xml | 4 + app/src/main/res/values-zh/strings.xml | 4 + app/src/main/res/values/strings.xml | 4 + .../alarms/backup/AlarmChannelRestoreTest.kt | 18 +- .../notifications/NotificationChannelsTest.kt | 197 +++++++++- 37 files changed, 945 insertions(+), 214 deletions(-) diff --git a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt index 3c52fe9f..0d4b8779 100644 --- a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/alarms/AlarmDatabaseInstrumentedTest.kt @@ -19,6 +19,7 @@ import android.content.Context import android.content.ContextWrapper import android.database.sqlite.SQLiteDatabase import android.media.AudioAttributes +import android.media.RingtoneManager import android.net.Uri import android.os.Bundle import androidx.lifecycle.SavedStateHandle @@ -29,6 +30,7 @@ import codes.swistak.batterymonitor.alarms.backup.Version2AlarmImporter import codes.swistak.batterymonitor.monitoring.notifications.NotificationChannels import codes.swistak.batterymonitor.testsupport.awaitCondition import codes.swistak.batterymonitor.testsupport.runOnMain +import codes.swistak.batterymonitor.ui.alarms.AlarmChannelSaveAction import codes.swistak.batterymonitor.ui.alarms.AlarmDraft import codes.swistak.batterymonitor.ui.alarms.AlarmsState import codes.swistak.batterymonitor.ui.alarms.AlarmsViewModel @@ -96,10 +98,7 @@ class AlarmDatabaseInstrumentedTest { ).use { it.execSQL(statement) } } - @Test - fun switching_stream_on_a_blocked_silent_channel_preserves_both_settings_in_android() { - val type = "charge_drops" - val manager = context.getSystemService(NotificationManager::class.java) + private fun assumeIsolatedChannels(manager: NotificationManager) { assumeFalse( "The isolated alarm database requires a clean notification environment", manager.notificationChannels.any { it.id.startsWith("alarm_settings_") } || @@ -109,6 +108,58 @@ class AlarmDatabaseInstrumentedTest { )) } ) + } + + @Test + fun recovering_a_dedicated_threshold_restores_its_own_tone_and_importance() { + val manager = context.getSystemService(NotificationManager::class.java) + assumeIsolatedChannels(manager) + val type = "charge_drops" + val parentId = "test-silent-${UUID.randomUUID()}" + val customId = "alarm_settings_${UUID.randomUUID()}" + val customSettings = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS) + val tone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM) + try { + manager.createNotificationChannel( + NotificationChannel(parentId, "Silent parent", NotificationManager.IMPORTANCE_HIGH) + .apply { setSound(null, null) } + ) + val audio = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build() + manager.createNotificationChannel( + NotificationChannel( + customId, + "Audible threshold", + NotificationManager.IMPORTANCE_DEFAULT + ) + .apply { setSound(tone, audio) } + ) + database.saveSharedSettings(type, null, AlarmConfiguration(channelId = parentId)) + val alarmId = database.saveThreshold(type, "17", emptyList()) + database.saveCustomSettings( + group(type, 17), + null, + AlarmConfiguration(customSettings, customId) + ) + manager.deleteNotificationChannel(customId) + assertNull(manager.getNotificationChannel(customId)) + + assertEquals(customId, NotificationChannels.ensureAlarmChannel(context, type, alarmId)) + val recovered = requireNotNull(manager.getNotificationChannel(customId)) + assertEquals(tone, recovered.sound) + assertEquals(NotificationManager.IMPORTANCE_DEFAULT, recovered.importance) + assertNull(manager.getNotificationChannel(parentId).sound) + } finally { + manager.deleteNotificationChannel(customId) + manager.deleteNotificationChannel(parentId) + } + } + + @Test + fun switching_stream_on_a_blocked_silent_channel_preserves_both_settings_in_android() { + val type = "charge_drops" + val manager = context.getSystemService(NotificationManager::class.java) + assumeIsolatedChannels(manager) val source = NotificationChannel( "test-blocked-${UUID.randomUUID()}", "Blocked source", @@ -138,7 +189,7 @@ class AlarmDatabaseInstrumentedTest { manager.deleteNotificationChannel(source.id) } } - + @Test fun reads_never_create_events_and_first_on_creates_only_one_persistent_record() { assertTrue(rows().isEmpty()) @@ -527,6 +578,70 @@ class AlarmDatabaseInstrumentedTest { runOnMain { condition(model.state.value) } } + @Test + fun threshold_settings_report_the_registered_stream_until_the_user_repairs_it() { + val manager = context.getSystemService(NotificationManager::class.java) + assumeIsolatedChannels(manager) + val type = "charge_drops" + val oldId = "alarm_settings_${UUID.randomUUID()}" + val request = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS) + val configuration = AlarmConfiguration(request, oldId) + val thresholdId = database.saveThreshold(type, "17", emptyList()) + val threshold = group(type, 17) + val tone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) + try { + val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build() + manager.createNotificationChannel( + NotificationChannel( + oldId, + "Existing threshold", + NotificationManager.IMPORTANCE_DEFAULT + ) + .apply { setSound(tone, attributes) } + ) + database.saveCustomSettings(threshold, null, configuration) + val viewModel = model() + main { viewModel.refresh() } + idle(viewModel) + val mismatch = + requireNotNull(viewModel.state.value.channelFor(type, thresholdId)?.usageMismatch) + assertEquals(AlarmVolumeCategory.ALARMS, mismatch.requested) + assertEquals(AudioAttributes.USAGE_NOTIFICATION, mismatch.registeredUsage) + + fun save(action: AlarmChannelSaveAction) { + main { + viewModel.saveAlarmSettings( + type, + threshold, + configuration, + request, + action + ) {} + } + idle(viewModel) + } + save(AlarmChannelSaveAction.SAVE) + assertEquals(mismatch, viewModel.state.value.savedUsageMismatch) + assertEquals(R.string.alarms_volume_mismatch, viewModel.state.value.notice) + assertEquals(configuration, database.getSnapshot().custom.getValue(thresholdId)) + + save(AlarmChannelSaveAction.REPAIR) + val repaired = database.getSnapshot().custom.getValue(thresholdId) + assertFalse(oldId == repaired.channelId) + assertEquals(request, repaired.sound) + val newChannel = + requireNotNull(manager.getNotificationChannel(requireNotNull(repaired.channelId))) + assertEquals(tone, newChannel.sound) + assertEquals(AudioAttributes.USAGE_ALARM, newChannel.audioAttributes.usage) + assertNull(viewModel.state.value.channelFor(type, thresholdId)?.usageMismatch) + assertNull(viewModel.state.value.savedUsageMismatch) + } finally { + database.getSnapshot().custom[thresholdId]?.channelId?.let(manager::deleteNotificationChannel) + manager.deleteNotificationChannel(oldId) + } + } + @Test fun view_model_reloads_once_per_commit_and_never_saves_while_typing_or_refreshing() { val model = model() diff --git a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/ui/dialogs/DialogEditingInstrumentedTest.kt b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/ui/dialogs/DialogEditingInstrumentedTest.kt index c3c60838..3330cb9a 100644 --- a/app/src/androidTest/kotlin/codes/swistak/batterymonitor/ui/dialogs/DialogEditingInstrumentedTest.kt +++ b/app/src/androidTest/kotlin/codes/swistak/batterymonitor/ui/dialogs/DialogEditingInstrumentedTest.kt @@ -14,6 +14,7 @@ package codes.swistak.batterymonitor.ui.dialogs import android.content.Context import android.content.ContextWrapper +import android.media.AudioAttributes import android.os.Build import androidx.activity.compose.setContent import androidx.compose.runtime.Composable @@ -34,12 +35,14 @@ import codes.swistak.batterymonitor.alarms.AlarmConfiguration import codes.swistak.batterymonitor.alarms.AlarmPlayback import codes.swistak.batterymonitor.alarms.AlarmSoundSettings import codes.swistak.batterymonitor.alarms.AlarmVolumeCategory +import codes.swistak.batterymonitor.monitoring.notifications.AlarmAudioUsageMismatch import codes.swistak.batterymonitor.settings.SettingsContract import codes.swistak.batterymonitor.testsupport.ComposeTestActivity import codes.swistak.batterymonitor.testsupport.awaitCondition import codes.swistak.batterymonitor.testsupport.clickSemantics import codes.swistak.batterymonitor.testsupport.composeWindowNodes import codes.swistak.batterymonitor.testsupport.dispatchComposeDialogBack +import codes.swistak.batterymonitor.ui.alarms.AlarmChannelSaveAction import codes.swistak.batterymonitor.ui.alarms.AlarmDraft import codes.swistak.batterymonitor.ui.alarms.AlarmSettingsDialog import codes.swistak.batterymonitor.ui.alarms.AlarmsState @@ -275,9 +278,10 @@ class DialogEditingInstrumentedTest { onRetry = {}, onDismiss = { visible.value = false }, onChannelSettings = { error("A new override has no channel") }, - onSave = { expected, sound, confirmed -> + usageMismatch = null, + onSave = { expected, sound, action -> assertNull(expected) - assertFalse(confirmed) + assertEquals(AlarmChannelSaveAction.SAVE, action) saved += sound visible.value = false }) @@ -301,7 +305,7 @@ class DialogEditingInstrumentedTest { fun replacing_a_channel_requires_confirmation_and_keeps_playback_draft() = withHost { val visible = mutableStateOf(true) val original = AlarmConfiguration(channelId = "synthetic-channel") - val saved = mutableListOf>() + val saved = mutableListOf>() show { if (visible.value) AlarmSettingsDialog( subject = "Synthetic alarm type", @@ -315,9 +319,10 @@ class DialogEditingInstrumentedTest { onRetry = {}, onDismiss = { visible.value = false }, onChannelSettings = {}, - onSave = { expected, sound, confirmed -> + usageMismatch = null, + onSave = { expected, sound, action -> assertEquals(expected, original) - saved += sound to confirmed + saved += sound to action visible.value = false }) } @@ -344,11 +349,74 @@ class DialogEditingInstrumentedTest { listOf( AlarmSoundSettings( AlarmPlayback.REPEAT, AlarmVolumeCategory.MEDIA - ) to true + ) to AlarmChannelSaveAction.REPLACE ), saved ) } + @Test + fun registered_usage_is_visible_and_repair_requires_explicit_confirmation() = withHost { + val stored = AlarmConfiguration( + sound = AlarmSoundSettings(AlarmPlayback.ONCE, AlarmVolumeCategory.MEDIA), + channelId = "dedicated-threshold" + ) + val visible = mutableStateOf(true) + val saved = mutableListOf() + show { + if (visible.value) AlarmSettingsDialog( + subject = "Threshold", + initialSound = stored.sound, + stored = stored, + creating = false, + enabled = true, + busy = false, + readError = null, + error = null, + onRetry = {}, + onDismiss = { visible.value = false }, + onChannelSettings = {}, + usageMismatch = AlarmAudioUsageMismatch( + AlarmVolumeCategory.MEDIA, AudioAttributes.USAGE_NOTIFICATION + ), + onSave = { expected, sound, action -> + assertEquals(expected, stored) + assertEquals(stored.sound, sound) + saved += action + visible.value = false + }) + } + val media = target.getString(R.string.alarms_volume_media) + val notifications = target.getString(R.string.alarms_volume_notifications) + val mismatch = target.getString(R.string.alarms_volume_mismatch, media, notifications) + val retry = target.getString(R.string.alarms_retry_volume) + val confirmation = target.getString(R.string.alarms_replace_channel_message) + val mediaHelp = target.getString(R.string.alarms_volume_media_help) + + awaitSelected(media) + await { displays(mismatch) } + assertEquals(Build.VERSION.SDK_INT >= 35, displays(mediaHelp)) + click(retry) + await { displays(confirmation) } + assertTrue(saved.isEmpty()) + click(target.getString(R.string.cancel)) + await { displays(mismatch) } + click(target.getString(R.string.charging_diagnostics_save)) + await { dialogs() == 0 } + assertEquals(listOf(AlarmChannelSaveAction.SAVE), saved) + + main { visible.value = true } + await { displays(mismatch) } + click(retry) + await { displays(confirmation) } + click(retry) + await { dialogs() == 0 } + assertEquals(listOf(AlarmChannelSaveAction.SAVE, AlarmChannelSaveAction.REPAIR), saved) + } + + private fun displays(text: String) = nodes().any { node -> + node.config.getOrNull(SemanticsProperties.Text)?.any { it.text == text } == true + } + private fun awaitSelected(label: String) = await("The selected alarm setting did not update") { nodes().any { node -> node.config.getOrNull(SemanticsProperties.Selected) == true && node.config.getOrNull( diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/app/BatteryInfoActivity.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/app/BatteryInfoActivity.kt index ce7b1ffe..a464c37f 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/app/BatteryInfoActivity.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/app/BatteryInfoActivity.kt @@ -406,9 +406,9 @@ class BatteryInfoActivity : AppCompatActivity() { ) } }, - onSaveSettings = { type, alarm, expected, sound, confirmed, onSaved -> + onSaveSettings = { type, alarm, expected, sound, action, onSaved -> alarms.saveAlarmSettings( - type, alarm, expected, sound, confirmed + type, alarm, expected, sound, action ) { onSaved() persistent.reloadSettings() diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt index 78597fc6..ad939035 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/AlarmNotifications.kt @@ -79,9 +79,7 @@ internal object AlarmNotifications { val details = "$eventDetails ${NotificationChannels.registeredAlarmDetails(channel)} " + "groupBlocked=$groupBlocked ${ audioState( - context, - manager, - stream + context, manager, stream ) }" val skipReason = when { @@ -179,8 +177,7 @@ internal object AlarmNotifications { alarm == null || config == null -> "rule disabled or removed" thresholdId != null && alarm.threshold != value -> "threshold changed" NotificationChannels.alarmChannelId( - alarm.type, - config + alarm.type, config ) != notification.channelId -> "channel changed" (config.sound.playback == AlarmPlayback.REPEAT) != repeating -> "playback mode changed" diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt index ef79db97..e6b65e3f 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannels.kt @@ -44,6 +44,17 @@ import java.text.NumberFormat import java.util.UUID import kotlin.math.roundToInt +internal data class AlarmAudioUsageMismatch( + val requested: AlarmVolumeCategory, val registeredUsage: Int? +) + +internal data class AlarmSettingsSaveResult( + val channelsSynced: Boolean, val usageMismatch: AlarmAudioUsageMismatch? +) + +internal class AlarmChannelRegistrationException(message: String, cause: Throwable? = null) : + IllegalStateException(message, cause) + internal object NotificationChannels { const val CHAN_ID_MAIN = "main_004" const val CHAN_ID_LIVE_UPDATE = "live_update_001" @@ -93,12 +104,25 @@ internal object NotificationChannels { val configuration = if (alarmId == null) snapshot.effective(type) else snapshot.custom[alarmId] ?: return@withAlarmChannelLock null val id = alarmChannelId(type, configuration) - syncAlarmGroup(context, manager, createIfMissing = true) - if (id == type) ensureChannel( - context, manager, alarmDefinitions.getValue(type), sound = configuration.sound - ) + if (registeredChannel(manager, id) != null) return@withAlarmChannelLock id + if (id == type) { + syncAlarmGroup(context, manager, createIfMissing = true) + createAlarmChannel( + context, + manager, + alarmDefinitions.getValue(type), + id, + null, + configuration.sound, + null, + recreating = true + ) + return@withAlarmChannelLock id + } syncManagedAlarms(context, manager, snapshot, createMissing = true) - id.takeIf { manager.getNotificationChannel(it) != null } + registeredChannel(manager, id)?.id ?: throw AlarmChannelRegistrationException( + "Could not recover alarm channel=$id type=$type thresholdId=$alarmId" + ) } fun saveAlarmSettings( @@ -108,7 +132,8 @@ internal object NotificationChannels { alarm: LogicalAlarm?, expected: AlarmConfiguration?, sound: AlarmSoundSettings, - replacementConfirmed: Boolean + replacementConfirmed: Boolean, + repairChannel: Boolean = false ) = withAlarmChannelLock(context) { require(alarm == null || alarm.type == type && alarm.thresholdKey != null) val definition = alarmDefinitions.getValue(type) @@ -118,11 +143,19 @@ internal object NotificationChannels { val manager = context.getSystemService(NotificationManager::class.java) val fallback = snapshot.effective(type) - val currentId = alarmChannelId(type, current ?: fallback) - val registered = manager.getNotificationChannel(currentId) - val existing = if (registered == null && (current ?: fallback).channelId != null) { - val parent = manager.getNotificationChannel(alarmChannelId(type, fallback)) - ?: manager.getNotificationChannel(type) + val previous = current ?: fallback + val createCustom = alarm != null && current == null + if (repairChannel) { + require(replacementConfirmed && !createCustom && previous.sound.volumeCategory == sound.volumeCategory) + } + val currentId = alarmChannelId(type, previous) + val registered = registeredChannel(manager, currentId) + val existing = if (registered == null && (previous.channelId != null || repairChannel)) { + val parent = + registeredChannel(manager, alarmChannelId(type, fallback)) ?: registeredChannel( + manager, + type + ) syncAlarmGroup(context, manager, createIfMissing = true) createAlarmChannel( context, @@ -130,26 +163,46 @@ internal object NotificationChannels { definition, currentId, if (current == null) null else alarm?.thresholdKey, - (current ?: fallback).sound, + previous.sound, parent, recreating = true ) } else registered - val createCustom = alarm != null && current == null - val changeChannel = shouldChangeAlarmChannel((current ?: fallback).sound, sound, existing) + val retryMismatch = + repairChannel && audioUsageMismatch(sound.volumeCategory, existing) != null + if (repairChannel) { + Log.i( + "NotificationChannels", + "Alarm channel repair type=$type thresholdId=${alarm?.id} " + "channel=$currentId requested=${sound.volumeCategory} replacing=$retryMismatch " + registeredAlarmDetails( + existing + ) + ) + } + val changeChannel = shouldChangeAlarmChannel(previous.sound, sound, existing) check(!changeChannel || createCustom || registered == null || replacementConfirmed) - val staged = if (createCustom || changeChannel) newChannelId() else null - val id = staged ?: current?.channelId - try { - if (staged != null) { + val staged = if (createCustom || changeChannel || retryMismatch) newChannelId() else null + val mismatch = try { + val replacement = staged?.let { id -> syncAlarmGroup(context, manager, createIfMissing = true) - createAlarmChannel( - context, manager, definition, staged, alarm?.thresholdKey, sound, existing + val candidate = createAlarmChannel( + context, manager, definition, id, alarm?.thresholdKey, sound, existing ) + if (retryMismatch && registeredVolumeCategory(candidate.audioAttributes?.usage) != sound.volumeCategory) { + Log.w( + "NotificationChannels", + "Repair retained channel=$currentId type=$type " + "thresholdId=${alarm?.id} requested=${sound.volumeCategory} " + "candidate=$id ${ + registeredAlarmDetails(candidate) + }" + ) + deleteStagedAlarmChannel(manager, id) + null + } else candidate } - val configuration = AlarmConfiguration(sound, id) + val configuration = AlarmConfiguration(sound, replacement?.id ?: current?.channelId) + val usageMismatch = audioUsageMismatch(sound.volumeCategory, replacement ?: existing) if (alarm == null) database.saveSharedSettings(type, expected, configuration) else database.saveCustomSettings(alarm, expected, configuration) + usageMismatch } catch (failure: Exception) { Log.w( "NotificationChannels", @@ -158,15 +211,35 @@ internal object NotificationChannels { staged?.let { deleteStagedAlarmChannel(manager, it) } throw failure } - reconcileSavedAlarms(context, manager, database) + AlarmSettingsSaveResult(reconcileSavedAlarms(context, manager, database), mismatch) + } + + fun audioUsageMismatch( + requested: AlarmVolumeCategory, channel: NotificationChannel? + ): AlarmAudioUsageMismatch? { + if (channel?.sound == null || channel.importance < NotificationManager.IMPORTANCE_DEFAULT) return null + val actual = channel.audioAttributes?.usage + return if (registeredVolumeCategory(actual) == requested) null else AlarmAudioUsageMismatch( + requested, actual + ) + } + + @Suppress("DEPRECATION") + fun registeredVolumeCategory(usage: Int?): AlarmVolumeCategory? = when (usage) { + AudioAttributes.USAGE_NOTIFICATION_EVENT, AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_REQUEST, AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT, AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_DELAYED -> AlarmVolumeCategory.NOTIFICATIONS + + else -> AlarmVolumeCategory.entries.firstOrNull { it.audioUsage == usage } } private fun shouldChangeAlarmChannel( previous: AlarmSoundSettings, requested: AlarmSoundSettings, channel: NotificationChannel? - ): Boolean = - previous.volumeCategory != requested.volumeCategory && channel?.audioAttributes != alarmAudioAttributes( - requested.volumeCategory + ): Boolean { + if (previous.volumeCategory == requested.volumeCategory) return false + val registered = channel?.audioAttributes ?: return true + return registeredVolumeCategory(registered.usage) != requested.volumeCategory || registered != alarmAudioAttributes( + registered.usage ) + } private fun deleteStagedAlarmChannel(manager: NotificationManager, id: String) { runCatching { manager.deleteNotificationChannel(id) }.onFailure { @@ -213,9 +286,9 @@ internal object NotificationChannels { fallbackId: String ): String? { val previousId = previous?.channelId ?: definition.id.takeIf { key == null } - val registered = - previousId?.let(manager::getNotificationChannel) ?: previous?.channelId?.let { id -> - staged += id + val registered = previousId?.let { registeredChannel(manager, it) } + ?: previous?.channelId?.let { id -> + // This ID still belongs to the current database if the restore rolls back. syncAlarmGroup(context, manager, createIfMissing = true) createAlarmChannel( context, @@ -224,7 +297,7 @@ internal object NotificationChannels { id, key, previous.sound, - manager.getNotificationChannel(fallbackId), + registeredChannel(manager, fallbackId), recreating = true ) } @@ -244,7 +317,7 @@ internal object NotificationChannels { id, key, sound, - registered ?: manager.getNotificationChannel(fallbackId) + registered ?: registeredChannel(manager, fallbackId) ) return id } @@ -310,14 +383,20 @@ internal object NotificationChannels { withAlarmChannelLock(context) { val manager = context.getSystemService(NotificationManager::class.java) val snapshot = readAlarmSnapshot(context) + var originalsSynced = true if (ensureOriginals) { - syncAlarmGroup(context, manager, createIfMissing = true) + try { + syncAlarmGroup(context, manager, createIfMissing = true) + } catch (_: AlarmChannelRegistrationException) { + originalsSynced = false + } for ((type, definition) in alarmDefinitions) { val active = snapshot.effective(type) if (alarmChannelId(type, active) != type) continue try { ensureChannel(context, manager, definition, sound = active.sound) } catch (failure: RuntimeException) { + originalsSynced = false Log.w( "NotificationChannels", "Could not initialize alarm channel=$type error=${failure.javaClass.simpleName}" @@ -326,7 +405,7 @@ internal object NotificationChannels { } } AlarmNotifications.reconcileConfiguration(context, snapshot) - syncManagedAlarms(context, manager, snapshot, createMissing = true) + syncManagedAlarms(context, manager, snapshot, createMissing = true) && originalsSynced } private fun readAlarmSnapshot(context: Context): AlarmSnapshot { @@ -345,11 +424,12 @@ internal object NotificationChannels { val snapshot = database.getSnapshot() AlarmNotifications.reconcileConfiguration(context, snapshot) syncManagedAlarms(context, manager, snapshot, createMissing = true) - }.onFailure { + }.getOrElse { Log.w( "NotificationChannels", "Could not reconcile saved alarm channels", it ) - }.isSuccess + false + } } private fun restoreMayReplaceChannels( @@ -359,12 +439,12 @@ internal object NotificationChannels { custom: Map ): Boolean = alarmDefinitions.keys.any { type -> val previous = current.effective(type) - val channel = manager.getNotificationChannel(alarmChannelId(type, previous)) + val channel = registeredChannel(manager, alarmChannelId(type, previous)) channel != null && shouldChangeAlarmChannel( previous.sound, shared[type] ?: AlarmSoundSettings(), channel ) } || customByThreshold(current).any { (key, previous) -> - val channel = previous.channelId?.let(manager::getNotificationChannel) ?: return@any false + val channel = previous.channelId?.let { registeredChannel(manager, it) } ?: return@any false val requested = custom[key] requested == null || shouldChangeAlarmChannel(previous.sound, requested, channel) } @@ -383,7 +463,20 @@ internal object NotificationChannels { manager: NotificationManager, snapshot: AlarmSnapshot, createMissing: Boolean - ) { + ): Boolean { + var allSynced = true + fun syncOne(id: String, operation: () -> Unit) { + try { + operation() + } catch (failure: RuntimeException) { + allSynced = false + Log.w( + "NotificationChannels", + "Could not synchronize alarm channel=$id error=${failure.javaClass.simpleName}" + ) + } + } + val retained = mutableSetOf() fun sync( definition: Definition, @@ -393,34 +486,38 @@ internal object NotificationChannels { ) { val id = configuration.channelId ?: return retained += id - val channel = manager.getNotificationChannel(id) - if (channel != null) { - refreshName(manager, channel, alarmName(context, definition, key)) - } else if (createMissing) { - syncAlarmGroup(context, manager, createIfMissing = true) - createAlarmChannel( - context, - manager, - definition, - id, - key, - configuration.sound, - manager.getNotificationChannel(sourceId) ?: manager.getNotificationChannel( - definition.id - ), - recreating = true - ) + syncOne(id) { + val channel = manager.getNotificationChannel(id) + if (channel != null) { + refreshName(manager, channel, alarmName(context, definition, key)) + } else if (createMissing) { + syncAlarmGroup(context, manager, createIfMissing = true) + createAlarmChannel( + context, + manager, + definition, + id, + key, + configuration.sound, + manager.getNotificationChannel(sourceId) ?: manager.getNotificationChannel( + definition.id + ), + recreating = true + ) + } } } for ((type, definition) in alarmDefinitions) { val shared = snapshot.effective(type) sync(definition, null, shared, type) - val original = manager.getNotificationChannel(type) ?: continue - val name = context.getString(definition.name) - refreshName( - manager, original, if (alarmChannelId(type, shared) == type) name - else context.getString(R.string.alarm_inactive_channel_name, name) - ) + syncOne(type) { + val original = manager.getNotificationChannel(type) ?: return@syncOne + val name = context.getString(definition.name) + refreshName( + manager, original, if (alarmChannelId(type, shared) == type) name + else context.getString(R.string.alarm_inactive_channel_name, name) + ) + } } for ((key, configuration) in customByThreshold(snapshot)) { val definition = alarmDefinitions.getValue(key.type) @@ -431,12 +528,22 @@ internal object NotificationChannels { alarmChannelId(key.type, snapshot.effective(key.type)) ) } - for (channel in manager.notificationChannels) { + val channels = try { + manager.notificationChannels + } catch (failure: RuntimeException) { + Log.w( + "NotificationChannels", + "Could not list obsolete alarm channels error=${failure.javaClass.simpleName}" + ) + return false + } + for (channel in channels) { if (channel.id.startsWith(MANAGED_ALARM_PREFIX) && channel.id !in retained) { Log.i("NotificationChannels", "Removing obsolete alarm channel=${channel.id}") - manager.deleteNotificationChannel(channel.id) + syncOne(channel.id) { manager.deleteNotificationChannel(channel.id) } } } + return allSynced } private fun newChannelId(): String = MANAGED_ALARM_PREFIX + UUID.randomUUID().toString() @@ -467,6 +574,20 @@ internal object NotificationChannels { return context.getString(R.string.alarm_custom_channel_name, type, value) } + private inline fun channelOperation(description: String, operation: () -> T): T = try { + operation() + } catch (failure: RuntimeException) { + val cause = failure.cause ?: failure + Log.w( + "NotificationChannels", + "Failed to $description error=${cause.javaClass.name} at=${cause.stackTrace.firstOrNull()}" + ) + throw AlarmChannelRegistrationException("Failed to $description", failure) + } + + private fun registeredChannel(manager: NotificationManager, id: String): NotificationChannel? = + channelOperation("read alarm channel=$id") { manager.getNotificationChannel(id) } + private fun createAlarmChannel( context: Context, manager: NotificationManager, @@ -480,75 +601,71 @@ internal object NotificationChannels { val importance = source?.importance ?: NotificationManager.IMPORTANCE_HIGH val sound = if (source != null) source.sound else RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) - val attributes = alarmAudioAttributes(settings.volumeCategory) - val channel = - NotificationChannel(id, alarmName(context, definition, key), importance).apply { - group = CHAN_GROUP_ID_ALARMS - setSound(sound, attributes) - if (source == null) { - enableLights(true) - lightColor = -0xcc4a1b - vibrationPattern = longArrayOf(0, 500, 500, 500, 500, 1000, 1000, 1000, 1000) - enableVibration(true) - lockscreenVisibility = Notification.VISIBILITY_PUBLIC - } else { - description = source.description - enableLights(source.shouldShowLights()) - lightColor = source.lightColor - if (Build.VERSION.SDK_INT >= 35 && source.vibrationEffect != null) { - vibrationEffect = source.vibrationEffect - } else vibrationPattern = source.vibrationPattern - enableVibration(source.shouldVibrate()) - setShowBadge(source.canShowBadge()) - lockscreenVisibility = source.lockscreenVisibility - if (manager.isNotificationPolicyAccessGranted) setBypassDnd(source.canBypassDnd()) - } - } + val attributes = alarmAudioAttributes(settings.volumeCategory.audioUsage) + val registration = if (recreating) "existing-id" else "new-id" val request = - "type=${definition.id} threshold=${key?.threshold} channel=$id " + "source=${source?.id} stream=${settings.volumeCategory} playback=${settings.playback}" - val registered = try { + "type=${definition.id} threshold=${key?.threshold} channel=$id registration=$registration " + "source=${source?.id} stream=${settings.volumeCategory} requestedUsage=${attributes.usage} " + "requestedContentType=${attributes.contentType} requestedImportance=$importance " + "requestedHasSound=${sound != null} playback=${settings.playback}" + val registered = channelOperation("register alarm channel $request") { + val channel = + NotificationChannel(id, alarmName(context, definition, key), importance).apply { + group = CHAN_GROUP_ID_ALARMS + setSound(sound, attributes) + if (source == null) { + enableLights(true) + lightColor = -0xcc4a1b + vibrationPattern = + longArrayOf(0, 500, 500, 500, 500, 1000, 1000, 1000, 1000) + enableVibration(true) + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + } else { + description = source.description + enableLights(source.shouldShowLights()) + lightColor = source.lightColor + if (Build.VERSION.SDK_INT >= 35 && source.vibrationEffect != null) { + vibrationEffect = source.vibrationEffect + } else vibrationPattern = source.vibrationPattern + enableVibration(source.shouldVibrate()) + setShowBadge(source.canShowBadge()) + lockscreenVisibility = source.lockscreenVisibility + if (manager.isNotificationPolicyAccessGranted) setBypassDnd(source.canBypassDnd()) + } + } manager.createNotificationChannel(channel) - checkNotNull(manager.getNotificationChannel(id)) { - "Android did not register the alarm channel" - } - } catch (failure: RuntimeException) { - if (recreating) deleteStagedAlarmChannel(manager, id) - Log.w( - "NotificationChannels", - "Alarm channel registration failed $request error=${failure.javaClass.simpleName}" - ) - throw failure + manager.getNotificationChannel(id) + } ?: run { + Log.w("NotificationChannels", "Alarm channel missing after registration $request") + throw AlarmChannelRegistrationException("Android did not register the alarm channel") } val details = "$request ${registeredAlarmDetails(registered)}" val soundMatches = registered.sound == sound - if (registered.audioAttributes?.usage != attributes.usage || registered.audioAttributes?.contentType != attributes.contentType || registered.importance != importance || !soundMatches || (source != null && registered.canBypassDnd() != source.canBypassDnd())) { + if (registered.audioAttributes != attributes || registered.importance != importance || !soundMatches || (source != null && registered.canBypassDnd() != source.canBypassDnd())) { Log.w( "NotificationChannels", - "Android adjusted alarm channel settings $details requestedImportance=$importance " + "soundMatches=$soundMatches bypassDnd=${registered.canBypassDnd()}" + "Android adjusted alarm channel settings $details soundMatches=$soundMatches bypassDnd=${registered.canBypassDnd()}" ) } else { Log.i("NotificationChannels", "Registered alarm channel $details") } - val rejection = when { - importance == NotificationManager.IMPORTANCE_NONE && registered.importance != NotificationManager.IMPORTANCE_NONE -> "Android re-enabled a blocked alarm channel" - - sound == null && registered.sound != null -> "Android enabled sound on a silent alarm channel" - !recreating && !soundMatches -> "Android changed the selected alarm sound" - else -> null - } - if (rejection != null) { - if (recreating) deleteStagedAlarmChannel(manager, id) - error(rejection) + // Reusing an ID lets Android restore that channel's own settings. The parent only supplies defaults. + if (!recreating) { + if (source != null && registered.importance != importance) { + throw AlarmChannelRegistrationException("Android changed the alarm channel importance") + } + if (!soundMatches) { + throw AlarmChannelRegistrationException("Android changed the selected alarm sound") + } } return registered } - private fun alarmAudioAttributes(category: AlarmVolumeCategory): AudioAttributes { - val usage = when (category) { + private val AlarmVolumeCategory.audioUsage: Int + get() = when (this) { AlarmVolumeCategory.NOTIFICATIONS -> AudioAttributes.USAGE_NOTIFICATION AlarmVolumeCategory.ALARMS -> AudioAttributes.USAGE_ALARM AlarmVolumeCategory.MEDIA -> AudioAttributes.USAGE_MEDIA } + + private fun alarmAudioAttributes(usage: Int): AudioAttributes { return AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(usage).build() } @@ -650,12 +767,12 @@ internal object NotificationChannels { private fun syncAlarmGroup( context: Context, manager: NotificationManager, createIfMissing: Boolean - ) { + ) = channelOperation("synchronize alarm channel group=$CHAN_GROUP_ID_ALARMS") { val existing = manager.notificationChannelGroups.firstOrNull { it.id == CHAN_GROUP_ID_ALARMS } - if (existing == null && !createIfMissing) return + if (existing == null && !createIfMissing) return@channelOperation val name = context.getString(R.string.channel_group_name_alarms) - if (existing?.name?.toString() == name) return + if (existing?.name?.toString() == name) return@channelOperation val group = NotificationChannelGroup(CHAN_GROUP_ID_ALARMS, name) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) group.description = existing?.description diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/settings/SettingsFragment.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/settings/SettingsFragment.kt index 8dd903b5..379d0696 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/settings/SettingsFragment.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/settings/SettingsFragment.kt @@ -89,6 +89,7 @@ import codes.swistak.batterymonitor.monitoring.charginglimit.ChargingLimitConten import codes.swistak.batterymonitor.monitoring.charginglimit.ChargingTargetResolver import codes.swistak.batterymonitor.monitoring.charginglimit.ResolvedTarget import codes.swistak.batterymonitor.monitoring.charginglimit.TargetSource +import codes.swistak.batterymonitor.monitoring.notifications.AlarmChannelRegistrationException import codes.swistak.batterymonitor.monitoring.notifications.NotificationChannels import codes.swistak.batterymonitor.privileged.PrivilegedAccess import codes.swistak.batterymonitor.settings.backup.SettingsBackup @@ -418,16 +419,16 @@ class SettingsFragment : Fragment(), OnSharedPreferenceChangeListener { options = choice.labels(resources).map(CharSequence::toString), selected = setOf( when (key) { - SettingsContract.KEY_CHIP_SWITCHING_INTERVAL -> chipSwitchingIntervalChoiceIndex( - row.value as? String, values - ) + SettingsContract.KEY_CHIP_SWITCHING_INTERVAL -> chipSwitchingIntervalChoiceIndex( + row.value as? String, values + ) - SettingsContract.KEY_CHART_GAP_THRESHOLD_MINUTES -> values.indexOf( - row.value as? String - ).takeIf { it >= 0 } ?: values.indexOf("custom") + SettingsContract.KEY_CHART_GAP_THRESHOLD_MINUTES -> values.indexOf( + row.value as? String + ).takeIf { it >= 0 } ?: values.indexOf("custom") - else -> values.indexOf(row.value as? String) - }), + else -> values.indexOf(row.value as? String) + }), multiple = false, onConfirm = { selected -> changeSetting(key, values[selected.single()]) }) rememberPreferenceDialog(key) @@ -1307,7 +1308,16 @@ class SettingsFragment : Fragment(), OnSharedPreferenceChangeListener { } } + private fun alarmBackupError(failure: Throwable?): Int? = when (failure) { + is AlarmChannelRegistrationException -> R.string.alarms_channel_registration_error + is android.database.sqlite.SQLiteException -> R.string.alarms_database_error + else -> null + } + private fun backupFailureMessage(error: Int, failure: Throwable): String { + if (error == R.string.invalid_alarms_file || failure is AlarmChannelRegistrationException) { + alarmBackupError(failure)?.let { return getString(it) } + } if (failure is LogExportRecoveryException) return failure.message ?: getString(error) if (failure !is GeneralBackupRestoreException) { val storageFailure = @@ -1321,11 +1331,15 @@ class SettingsFragment : Fragment(), OnSharedPreferenceChangeListener { val failed = failure.failedData.joinToString(", ") { generalBackupItemLabel(it) } - return getString( + val summary = getString( R.string.settings_restore_partial, completed.ifEmpty { getString(R.string.settings_restore_none) }, failed ) + if (GeneralBackupDataType.ALARMS in failure.failedData) { + alarmBackupError(failure.cause)?.let { return "$summary\n\n${getString(it)}" } + } + return summary } private fun predictorExportRequest(): CompletableFuture? { diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmSettingsDialog.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmSettingsDialog.kt index aab8ff57..ec0ecdf3 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmSettingsDialog.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmSettingsDialog.kt @@ -7,6 +7,8 @@ */ package codes.swistak.batterymonitor.ui.alarms +import android.content.res.Resources +import android.os.Build import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -28,6 +30,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.heading @@ -38,9 +41,33 @@ import codes.swistak.batterymonitor.alarms.AlarmConfiguration import codes.swistak.batterymonitor.alarms.AlarmPlayback import codes.swistak.batterymonitor.alarms.AlarmSoundSettings import codes.swistak.batterymonitor.alarms.AlarmVolumeCategory +import codes.swistak.batterymonitor.monitoring.notifications.AlarmAudioUsageMismatch +import codes.swistak.batterymonitor.monitoring.notifications.NotificationChannels import codes.swistak.batterymonitor.ui.components.ActionLabel import codes.swistak.batterymonitor.ui.components.applicationDialogsAllowed +internal enum class AlarmChannelSaveAction { SAVE, REPLACE, REPAIR } + +private val AlarmVolumeCategory.label: Int + get() = when (this) { + AlarmVolumeCategory.NOTIFICATIONS -> R.string.alarms_volume_notifications + AlarmVolumeCategory.ALARMS -> R.string.alarms_volume_alarms + AlarmVolumeCategory.MEDIA -> R.string.alarms_volume_media + } + +internal fun Resources.describeAlarmUsageMismatch(mismatch: AlarmAudioUsageMismatch): String { + val usage = mismatch.registeredUsage + val category = NotificationChannels.registeredVolumeCategory(usage) + val registered = when { + category != null -> getString(category.label) + usage == null -> getString(R.string.status_unknown) + else -> "${getString(R.string.status_unknown)} ($usage)" + } + return getString( + R.string.alarms_volume_mismatch, getString(mismatch.requested.label), registered + ) +} + @Composable internal fun AlarmSettingsDialog( subject: String, @@ -54,7 +81,8 @@ internal fun AlarmSettingsDialog( onRetry: () -> Unit, onDismiss: () -> Unit, onChannelSettings: () -> Unit, - onSave: (AlarmConfiguration?, AlarmSoundSettings, Boolean) -> Unit + usageMismatch: AlarmAudioUsageMismatch?, + onSave: (AlarmConfiguration?, AlarmSoundSettings, AlarmChannelSaveAction) -> Unit ) { val originalPlayback = rememberSaveable { mutableStateOf(stored?.sound?.playback) }.value val originalVolume = rememberSaveable { mutableStateOf(stored?.sound?.volumeCategory) }.value @@ -64,33 +92,34 @@ internal fun AlarmSettingsDialog( } else null var playback by rememberSaveable { mutableStateOf(initialSound.playback) } var volume by rememberSaveable { mutableStateOf(initialSound.volumeCategory) } - var confirmReplacement by rememberSaveable { mutableStateOf(false) } + var confirmation by rememberSaveable { mutableStateOf(null) } if (!applicationDialogsAllowed()) return val stale = expected != stored val canSave = enabled && !stale val problem = if (stale) stringResource(R.string.alarms_conflict) else readError ?: error - if (confirmReplacement) { - AlertDialog( - onDismissRequest = { if (!busy) confirmReplacement = false }, - title = { Text(stringResource(R.string.alarms_replace_channel_title)) }, - text = { - Column(Modifier.verticalScroll(rememberScrollState())) { - Text(stringResource(R.string.alarms_replace_channel_message)) - problem?.let { Text(it, color = MaterialTheme.colorScheme.error) } - } - }, - confirmButton = { - TextButton( - onClick = { onSave(expected, AlarmSoundSettings(playback, volume), true) }, - enabled = canSave - ) { Text(stringResource(R.string.charging_diagnostics_save)) } - }, - dismissButton = { - TextButton(onClick = { confirmReplacement = false }, enabled = !busy) { - Text(stringResource(R.string.cancel)) - } - }) + val action = confirmation + if (action != null) { + val repair = action == AlarmChannelSaveAction.REPAIR + AlertDialog(onDismissRequest = { if (!busy) confirmation = null }, title = { + Text(stringResource(if (repair) R.string.alarms_retry_volume else R.string.alarms_replace_channel_title)) + }, text = { + Column(Modifier.verticalScroll(rememberScrollState())) { + Text(stringResource(R.string.alarms_replace_channel_message)) + problem?.let { Text(it, color = MaterialTheme.colorScheme.error) } + } + }, confirmButton = { + TextButton( + onClick = { onSave(expected, AlarmSoundSettings(playback, volume), action) }, + enabled = canSave + ) { + Text(stringResource(if (repair) R.string.alarms_retry_volume else R.string.charging_diagnostics_save)) + } + }, dismissButton = { + TextButton(onClick = { confirmation = null }, enabled = !busy) { + Text(stringResource(R.string.cancel)) + } + }) } else AlertDialog( onDismissRequest = { if (!busy) onDismiss() }, title = { Text(stringResource(R.string.alarm_settings_subtitle)) }, @@ -112,15 +141,24 @@ internal fun AlarmSettingsDialog( style = MaterialTheme.typography.bodySmall ) AlarmSettingsChoices( - label = R.string.alarms_volume_category, options = listOf( - AlarmVolumeCategory.NOTIFICATIONS to R.string.alarms_volume_notifications, - AlarmVolumeCategory.ALARMS to R.string.alarms_volume_alarms, - AlarmVolumeCategory.MEDIA to R.string.alarms_volume_media - ), selected = volume, enabled = canSave, onSelect = { volume = it }) - Text( - stringResource(R.string.alarms_volume_help), - style = MaterialTheme.typography.bodySmall - ) + label = R.string.alarms_volume_category, + options = AlarmVolumeCategory.entries.map { it to it.label }, + selected = volume, + enabled = canSave, + onSelect = { volume = it }) + val volumeHelp = + if (volume == AlarmVolumeCategory.MEDIA && Build.VERSION.SDK_INT >= 35) R.string.alarms_volume_media_help else R.string.alarms_volume_help + Text(stringResource(volumeHelp), style = MaterialTheme.typography.bodySmall) + if (!creating && usageMismatch != null && volume == usageMismatch.requested) { + Text( + LocalResources.current.describeAlarmUsageMismatch(usageMismatch), + style = MaterialTheme.typography.bodySmall + ) + TextButton( + onClick = { confirmation = AlarmChannelSaveAction.REPAIR }, + enabled = canSave && playback == initialSound.playback + ) { Text(stringResource(R.string.alarms_retry_volume)) } + } if (!creating) TextButton(onClick = onChannelSettings, enabled = !busy) { ActionLabel( stringResource(R.string.alarms_android_channel_settings), @@ -139,8 +177,8 @@ internal fun AlarmSettingsDialog( val sound = AlarmSoundSettings(playback, volume) val currentVolume = originalVolume ?: AlarmVolumeCategory.NOTIFICATIONS val replacesChannel = !creating && sound.volumeCategory != currentVolume - if (replacesChannel) confirmReplacement = true - else onSave(expected, sound, false) + if (replacesChannel) confirmation = AlarmChannelSaveAction.REPLACE + else onSave(expected, sound, AlarmChannelSaveAction.SAVE) }, enabled = canSave ) { Text(stringResource(R.string.charging_diagnostics_save)) } }, diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsScreen.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsScreen.kt index 77866cb1..46e8f8e9 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsScreen.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsScreen.kt @@ -111,7 +111,7 @@ internal fun AlarmsScreen( onAdd: (String) -> Unit, onEnabled: (String, LogicalAlarm?, Boolean) -> Unit, onChannelSettings: (String, Int?) -> Unit, - onSaveSettings: (String, LogicalAlarm?, AlarmConfiguration?, AlarmSoundSettings, Boolean, () -> Unit) -> Unit, + onSaveSettings: (String, LogicalAlarm?, AlarmConfiguration?, AlarmSoundSettings, AlarmChannelSaveAction, () -> Unit) -> Unit, onRemoveCustomSettings: (LogicalAlarm, AlarmConfiguration) -> Unit, onNotificationSettings: () -> Unit, onTargetSettings: (String) -> Unit, @@ -163,13 +163,17 @@ internal fun AlarmsScreen( onRevealHandled() } } - LaunchedEffect(state.notice) { + LaunchedEffect(state.notice, state.savedUsageMismatch) { state.notice?.let { notice -> if (notice == R.string.alarms_saved) { onNoticeHandled() context.showToast(notice, Toast.LENGTH_SHORT) } else { - snackbar.showSnackbar(resources.getString(notice)) + val message = + if (notice == R.string.alarms_volume_mismatch && state.savedUsageMismatch != null) { + resources.describeAlarmUsageMismatch(state.savedUsageMismatch) + } else resources.getString(notice) + snackbar.showSnackbar(message) onNoticeHandled() } } @@ -431,14 +435,19 @@ internal fun AlarmsScreen( enabled = state.canMutate, busy = state.busy, readError = state.readError, - error = if (state.notice == R.string.alarms_settings_unavailable) { - stringResource(R.string.alarms_settings_unavailable) - } else state.error, + error = when (state.notice) { + R.string.alarms_settings_unavailable, R.string.alarms_channel_registration_error, R.string.alarms_database_error -> stringResource( + state.notice + ) + + else -> state.error + }, onRetry = onRetry, onDismiss = { settingsType = null }, onChannelSettings = { onChannelSettings(type, alarmId) }, - onSave = { expected, sound, replacementConfirmed -> - onSaveSettings(type, alarm, expected, sound, replacementConfirmed) { + usageMismatch = state.channelFor(type, alarmId)?.usageMismatch, + onSave = { expected, sound, action -> + onSaveSettings(type, alarm, expected, sound, action) { settingsType = null } }) @@ -503,7 +512,7 @@ private fun AlarmTypeHeader( onTargets: () -> Unit ) { val label = stringResource(alarmTypeLabel(definition.type)) - val channel = state.channels[definition.type] + val channel = state.channelFor(definition.type) var options by rememberSaveable { mutableStateOf(false) } AlarmSurface(first, last) { if (!first) HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) diff --git a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt index 22346dc0..a3efd5e7 100644 --- a/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt +++ b/app/src/main/kotlin/codes/swistak/batterymonitor/ui/alarms/AlarmsViewModel.kt @@ -14,9 +14,11 @@ package codes.swistak.batterymonitor.ui.alarms import android.annotation.SuppressLint import android.app.Application +import android.app.NotificationChannel import android.app.NotificationManager import android.os.Build import android.os.Bundle +import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope @@ -38,6 +40,9 @@ import codes.swistak.batterymonitor.alarms.validStoredAlarm import codes.swistak.batterymonitor.monitoring.BackgroundServiceWatchdog import codes.swistak.batterymonitor.monitoring.charginglimit.ChargingLimitContentProvider import codes.swistak.batterymonitor.monitoring.charginglimit.ChargingLimitProvider +import codes.swistak.batterymonitor.monitoring.notifications.AlarmAudioUsageMismatch +import codes.swistak.batterymonitor.monitoring.notifications.AlarmChannelRegistrationException +import codes.swistak.batterymonitor.monitoring.notifications.AlarmSettingsSaveResult import codes.swistak.batterymonitor.monitoring.notifications.NotificationChannels import codes.swistak.batterymonitor.privileged.PrivilegedAccess import codes.swistak.batterymonitor.settings.SettingsContract @@ -52,7 +57,11 @@ import kotlinx.coroutines.withContext import java.util.Locale internal data class AlarmChannelInfo( - val available: Boolean, val blocked: Boolean, val sound: Boolean, val vibration: Boolean + val available: Boolean, + val blocked: Boolean, + val sound: Boolean, + val vibration: Boolean, + val usageMismatch: AlarmAudioUsageMismatch? = null ) internal data class AlarmsState( @@ -68,6 +77,7 @@ internal data class AlarmsState( val readError: String? = null, val error: String? = null, val notice: Int? = null, + val savedUsageMismatch: AlarmAudioUsageMismatch? = null, val draft: AlarmDraft? = null, val draftConflict: Boolean = false, val collisionId: Int? = null, @@ -77,6 +87,8 @@ internal data class AlarmsState( ) { val canMutate: Boolean get() = hasSnapshot && !loading && readError == null && !busy val enabledCount: Int? get() = if (hasSnapshot) projection.enabledCount else null + fun channelFor(type: String, alarmId: Int? = null): AlarmChannelInfo? = + channels[NotificationChannels.alarmChannelId(type, alarmSnapshot.effective(type, alarmId))] } internal class AlarmsViewModel( @@ -120,6 +132,7 @@ internal class AlarmsViewModel( draft = old.draft, error = old.error, notice = old.notice, + savedUsageMismatch = old.savedUsageMismatch, collisionId = old.collisionId, revealType = old.revealType, revealId = old.revealId, @@ -128,11 +141,9 @@ internal class AlarmsViewModel( } == true) } savedState.remove("alarm_pending_id")?.let(::openLegacyAlarm) - }, onFailure = { + }, onFailure = { failure -> mutableState.update { - it.copy( - loading = false, readError = text(R.string.alarms_database_error) - ) + it.copy(loading = false, readError = text(alarmAccessError(failure))) } }) } @@ -265,7 +276,8 @@ internal class AlarmsViewModel( mutate(onSuccess = onChanged) { it.deleteLogicalAlarm(listOf(rule)) } fun clearReveal() = mutableState.update { it.copy(revealType = null, revealId = null) } - fun clearNotice() = mutableState.update { it.copy(notice = null) } + fun clearNotice() = mutableState.update { it.copy(notice = null, savedUsageMismatch = null) } + fun reportSettingsFailure() = mutableState.update { it.copy(notice = R.string.alarms_settings_unavailable) } @@ -274,12 +286,16 @@ internal class AlarmsViewModel( fun openAlarmChannel(type: String, alarmId: Int?, open: (String) -> Boolean) { if (channelSettingsJob?.isActive == true) return channelSettingsJob = viewModelScope.launch { - val channelId = withContext(Dispatchers.IO) { + val result = withContext(Dispatchers.IO) { runCatching { NotificationChannels.ensureAlarmChannel(getApplication(), type, alarmId) - }.getOrNull() + } } - if (channelId == null || !open(channelId)) reportSettingsFailure() + result.fold(onSuccess = { channelId -> + if (channelId == null || !open(channelId)) reportSettingsFailure() + }, onFailure = { failure -> + mutableState.update { it.copy(notice = alarmAccessError(failure)) } + }) } } @@ -288,11 +304,18 @@ internal class AlarmsViewModel( alarm: LogicalAlarm?, expected: AlarmConfiguration?, sound: AlarmSoundSettings, - replacementConfirmed: Boolean, + action: AlarmChannelSaveAction, onSaved: () -> Unit ) = mutateAndSync(onSaved) { database -> NotificationChannels.saveAlarmSettings( - getApplication(), database, type, alarm, expected, sound, replacementConfirmed + getApplication(), + database, + type, + alarm, + expected, + sound, + replacementConfirmed = action != AlarmChannelSaveAction.SAVE, + repairChannel = action == AlarmChannelSaveAction.REPAIR ) } @@ -323,11 +346,15 @@ internal class AlarmsViewModel( private fun mutate(onSuccess: () -> Unit, operation: (AlarmDatabase) -> Unit) = mutateAndSync(onSuccess) { database -> - NotificationChannels.mutateAlarmRules(getApplication(), database, operation) + AlarmSettingsSaveResult( + NotificationChannels.mutateAlarmRules( + getApplication(), database, operation + ), null + ) } private fun mutateAndSync( - onSuccess: () -> Unit, operation: (AlarmDatabase) -> Boolean + onSuccess: () -> Unit, operation: (AlarmDatabase) -> AlarmSettingsSaveResult ) { if (!state.value.canMutate) return refreshJob?.cancel() @@ -336,12 +363,20 @@ internal class AlarmsViewModel( val result = withContext(Dispatchers.IO) { runCatching { withDatabase(operation) } } - result.fold(onSuccess = { channelsSynced -> + result.fold(onSuccess = { saved -> mutableState.update { it.copy(busy = false) } val notice = runCatching(onSuccess).fold(onSuccess = { - if (channelsSynced) R.string.alarms_saved else R.string.alarms_saved_channels_failed + when { + saved.usageMismatch != null -> R.string.alarms_volume_mismatch + saved.channelsSynced -> R.string.alarms_saved + else -> R.string.alarms_saved_channels_failed + } }, onFailure = { R.string.alarms_saved_reload_failed }) - mutableState.update { it.copy(notice = notice) } + mutableState.update { + it.copy( + notice = notice, savedUsageMismatch = saved.usageMismatch + ) + } refresh() }, onFailure = { failure -> mutableState.update { old -> @@ -350,7 +385,7 @@ internal class AlarmsViewModel( error = when (failure) { is AlarmCollisionException -> null is AlarmConflictException -> if (old.draft == null) text(R.string.alarms_conflict) else null - else -> text(R.string.alarms_database_error) + else -> text(alarmAccessError(failure)) }, draftConflict = old.draftConflict || failure is AlarmConflictException, collisionId = (failure as? AlarmCollisionException)?.existing?.id @@ -367,27 +402,50 @@ internal class AlarmsViewModel( getApplication().getSystemService(NotificationManager::class.java) val snapshot = withDatabase { it.getSnapshot() } val rules = snapshot.rules + val requestedByChannel = buildMap { + for (type in AlarmDatabase.SUPPORTED_TYPES) { + val shared = snapshot.effective(type) + put(NotificationChannels.alarmChannelId(type, shared), shared.sound.volumeCategory) + } + for ((sound, channelId) in snapshot.custom.values) { + channelId?.let { put(it, sound.volumeCategory) } + } + } + val registered: Map + val notificationsBlocked: Boolean + val groupBlocked: Boolean + try { + registered = manager.notificationChannels.associateBy { it.id } + notificationsBlocked = !manager.areNotificationsEnabled() + groupBlocked = Build.VERSION.SDK_INT >= 28 && manager.getNotificationChannelGroup( + NotificationChannels.CHAN_GROUP_ID_ALARMS + )?.isBlocked == true + } catch (failure: RuntimeException) { + Log.w( + "AlarmsViewModel", "Could not read alarm channels: ${failure.javaClass.simpleName}" + ) + throw AlarmChannelRegistrationException( + "Could not read alarm notification channels", failure + ) + } return AlarmsState( rules = rules, projection = projectAlarms(rules), alarmSnapshot = snapshot, hasSnapshot = true, monitoringDesired = BackgroundServiceWatchdog.isServiceDesired(getApplication()), - channels = AlarmDatabase.SUPPORTED_TYPES.associateWith { type -> - val channel = manager.getNotificationChannel( - NotificationChannels.alarmChannelId(type, snapshot.effective(type)) - ) + channels = requestedByChannel.mapValues { (id, requested) -> + val channel = registered[id] AlarmChannelInfo( available = channel != null, blocked = channel?.importance == NotificationManager.IMPORTANCE_NONE, sound = channel?.sound != null && channel.importance >= NotificationManager.IMPORTANCE_DEFAULT, - vibration = channel?.shouldVibrate() == true + vibration = channel?.shouldVibrate() == true, + usageMismatch = NotificationChannels.audioUsageMismatch(requested, channel) ) }, - notificationsBlocked = !manager.areNotificationsEnabled(), - groupBlocked = Build.VERSION.SDK_INT >= 28 && manager.getNotificationChannelGroup( - NotificationChannels.CHAN_GROUP_ID_ALARMS - )?.isBlocked == true, + notificationsBlocked = notificationsBlocked, + groupBlocked = groupBlocked, loading = false ) } @@ -402,6 +460,8 @@ internal class AlarmsViewModel( } private fun text(resource: Int): String = getApplication().getString(resource) + private fun alarmAccessError(failure: Throwable): Int = + if (failure is AlarmChannelRegistrationException) R.string.alarms_channel_registration_error else R.string.alarms_database_error } internal fun AlarmDraft.toBundle() = Bundle().apply { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index a37b73d2..22cc461c 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -346,6 +346,9 @@ المنبهات الوسائط يستخدم Android فئة مستوى الصوت المطلوبة إذا كان جهازك يدعمها. + قد يستخدم Android مستوى صوت الإشعارات لهذا المنبّه حتى عند اختيار الوسائط. + اخترت «%1$s». سجّل Android نوع استخدام الصوت لهذه القناة على أنه «%2$s». + إعادة المحاولة هل تريد تغيير فئة مستوى الصوت؟ يتطلب Android قناة إشعارات جديدة. ينسخ التطبيق إعدادات الصوت والاهتزاز والأهمية حيثما يسمح النظام بذلك. قد تعود خيارات الإشعارات الأخرى إلى إعداداتها الافتراضية. %1$s %2$s @@ -365,6 +368,7 @@ هذا المنبه مفقود أو غير صالح. راجع قائمة المنبهات. بعض المنبهات المحفوظة غير صالحة. راجع هذه السجلات؛ لم تتم إزالتها. تعذر الوصول إلى قاعدة بيانات المنبهات. أعد المحاولة. + تعذّر على Android إعداد قناة إشعارات المنبّه. يُرجى إعادة المحاولة. تم حفظ إعدادات المنبهات تم الحفظ، لكن تعذر إخطار المراقبة. راجع حالة المراقبة. تم الحفظ، لكن تعذر تحديث قنوات الإشعارات. راجع إعدادات إشعارات Android. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 20680850..6fd7b26a 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -339,6 +339,9 @@ Alarmy Média Android použije vybranou kategorii hlasitosti, pokud ji zařízení podporuje. + I při výběru médií může Android pro tento alarm použít hlasitost oznámení. + Vybraná kategorie hlasitosti je „%1$s“. Android pro tento kanál zaregistroval kategorii „%2$s“. + Zkusit znovu Změnit kategorii hlasitosti? Android vyžaduje nový kanál oznámení. Aplikace zkopíruje nastavení zvuku, vibrací a důležitosti v rozsahu, který systém umožňuje. Ostatní nastavení oznámení se mohou obnovit na výchozí hodnoty. %1$s %2$s @@ -358,6 +361,7 @@ Tento alarm chybí nebo je neplatný. Zkontrolujte katalog alarmů. Některé uložené alarmy jsou neplatné. Zkontrolujte tyto záznamy; nebyly odstraněny. Nelze přistoupit k databázi alarmů. Zkuste to znovu. + Androidu se nepodařilo nastavit kanál oznámení pro alarm. Zkuste to znovu. Nastavení alarmů uloženo Uloženo, ale sledování se nepodařilo upozornit. Zkontrolujte stav sledování. Uloženo, ale kanály oznámení se nepodařilo aktualizovat. Zkontrolujte nastavení oznámení Androidu. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 873c43a7..d787dd69 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -330,6 +330,9 @@ Alarme Medien Android verwendet die gewählte Lautstärkekategorie, sofern Ihr Gerät sie unterstützt. + Auch bei ausgewählter Medienlautstärke kann Android für diesen Alarm die Benachrichtigungslautstärke verwenden. + Sie haben „%1$s“ gewählt. Android hat diesen Kanal mit der Audiokategorie „%2$s“ registriert. + Erneut versuchen Lautstärkekategorie ändern? Android benötigt einen neuen Benachrichtigungskanal. Die App kopiert Ihre Einstellungen für Ton, Vibration und Wichtigkeit, soweit Android dies zulässt. Andere Benachrichtigungseinstellungen können zurückgesetzt werden. %1$s %2$s @@ -349,6 +352,7 @@ Dieser Alarm fehlt oder ist ungültig. Prüfen Sie den Alarmkatalog. Einige gespeicherte Alarme sind ungültig. Prüfen Sie diese Einträge; sie wurden nicht entfernt. Zugriff auf die Alarmdatenbank fehlgeschlagen. Versuchen Sie es erneut. + Android konnte den Benachrichtigungskanal für den Alarm nicht einrichten. Versuchen Sie es erneut. Alarmeinstellungen gespeichert Gespeichert, aber die Überwachung konnte nicht benachrichtigt werden. Prüfen Sie den Überwachungsstatus. Gespeichert, aber die Benachrichtigungskanäle konnten nicht aktualisiert werden. Prüfen Sie die Android-Benachrichtigungseinstellungen. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index f7bf9079..7bf6a6f1 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -330,6 +330,9 @@ Συναγερμοί Πολυμέσα Το Android χρησιμοποιεί την επιλεγμένη κατηγορία έντασης ήχου εφόσον την υποστηρίζει η συσκευή σας. + Ακόμη κι αν επιλέξετε «Πολυμέσα», το Android μπορεί να χρησιμοποιήσει την ένταση των ειδοποιήσεων για αυτόν τον συναγερμό. + Επιλέξατε «%1$s». Το Android καταχώρισε αυτό το κανάλι με κατηγορία ήχου «%2$s». + Νέα προσπάθεια Αλλαγή κατηγορίας έντασης ήχου; Το Android απαιτεί νέο κανάλι ειδοποιήσεων. Η εφαρμογή αντιγράφει τις ρυθμίσεις ήχου, δόνησης και σημασίας όπου το επιτρέπει το Android. Οι άλλες επιλογές ειδοποιήσεων ενδέχεται να επανέλθουν στις προεπιλογές. %1$s %2$s @@ -349,6 +352,7 @@ Αυτός ο συναγερμός λείπει ή δεν είναι έγκυρος. Ελέγξτε τον κατάλογο συναγερμών. Ορισμένοι αποθηκευμένοι συναγερμοί δεν είναι έγκυροι. Ελέγξτε αυτές τις εγγραφές· δεν έχουν αφαιρεθεί. Δεν ήταν δυνατή η πρόσβαση στη βάση δεδομένων συναγερμών. Δοκιμάστε ξανά. + Το Android δεν μπόρεσε να ρυθμίσει το κανάλι ειδοποιήσεων του συναγερμού. Δοκιμάστε ξανά. Οι ρυθμίσεις συναγερμών αποθηκεύτηκαν Αποθηκεύτηκε, αλλά δεν ήταν δυνατή η ενημέρωση της παρακολούθησης. Ελέγξτε την κατάσταση παρακολούθησης. Οι ρυθμίσεις αποθηκεύτηκαν, αλλά δεν ήταν δυνατή η ενημέρωση των καναλιών ειδοποιήσεων. Ελέγξτε τις ρυθμίσεις ειδοποιήσεων Android. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b0bfef7b..e13f26cd 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -334,6 +334,9 @@ Alarmas Contenido multimedia Android usa la categoría de volumen elegida si tu dispositivo la admite. + Aunque selecciones Contenido multimedia, Android puede reproducir esta alarma con el volumen de las notificaciones. + Has seleccionado «%1$s». Android ha registrado este canal con la categoría de audio «%2$s». + Reintentar ¿Cambiar la categoría de volumen? Android requiere un canal de notificaciones nuevo. La aplicación copia los ajustes de sonido, vibración e importancia en la medida en que Android lo permita. Es posible que se restablezcan otras opciones de notificaciones. %1$s %2$s @@ -353,6 +356,7 @@ Esta alarma falta o no es válida. Revisa el catálogo de alarmas. Algunas alarmas guardadas no son válidas. Revisa estos registros; no se han eliminado. No se ha podido acceder a la base de datos de alarmas. Inténtalo de nuevo. + Android no ha podido configurar el canal de notificaciones de la alarma. Inténtalo de nuevo. Ajustes de alarma guardados Guardado, pero no se ha podido avisar al monitor. Revisa el estado de monitorización. Se guardaron los ajustes, pero no se pudieron actualizar los canales de notificaciones. Revisa los ajustes de notificaciones de Android. diff --git a/app/src/main/res/values-fa/strings.xml b/app/src/main/res/values-fa/strings.xml index af64fd03..57cf29d1 100644 --- a/app/src/main/res/values-fa/strings.xml +++ b/app/src/main/res/values-fa/strings.xml @@ -330,6 +330,9 @@ آلارم‌ها رسانه اگر دستگاهتان پشتیبانی کند، Android از دستهٔ انتخاب‌شده برای میزان صدا استفاده می‌کند. + حتی اگر «رسانه» را انتخاب کنید، Android ممکن است این آلارم را با میزان صدای اعلان‌ها پخش کند. + «%1$s» را انتخاب کردید. Android این کانال را با دستهٔ صدای «%2$s» ثبت کرد. + تلاش دوباره دستهٔ میزان صدا تغییر کند؟ Android به کانال اعلان جدیدی نیاز دارد. برنامه تنظیمات صدا، لرزش و اهمیت را تا جایی که Android اجازه دهد کپی می‌کند. ممکن است سایر گزینه‌های اعلان بازنشانی شوند. %1$s %2$s @@ -349,6 +352,7 @@ این آلارم موجود نیست یا نامعتبر است. فهرست آلارمها را بررسی کنید. برخی آلارمهای ذخیره‌شده نامعتبرند. این رکوردها را بررسی کنید؛ حذف نشده‌اند. دسترسی به پایگاه داده آلارمها ممکن نشد. دوباره تلاش کنید. + Android نتوانست کانال اعلان آلارم را تنظیم کند. دوباره تلاش کنید. تنظیمات آلارم ذخیره شدند ذخیره شد، اما آگاه کردن پایشگر ممکن نشد. وضعیت پایش را بررسی کنید. تنظیمات ذخیره شد، اما کانال‌های اعلان به‌روز نشدند. تنظیمات اعلان‌های Android را بررسی کنید. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 7fa21ceb..21cac555 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -334,6 +334,9 @@ Alarmes Multimédia Android utilise la catégorie de volume choisie si votre appareil la prend en charge. + Même si vous sélectionnez Multimédia, Android peut utiliser le volume des notifications pour cette alarme. + Vous avez sélectionné « %1$s ». Android a enregistré ce canal avec la catégorie audio « %2$s ». + Réessayer Changer la catégorie de volume ? Android exige un nouveau canal de notification. L’application copie vos paramètres de son, de vibration et d’importance dans la mesure autorisée par Android. Les autres options de notification peuvent être réinitialisées. %1$s %2$s @@ -353,6 +356,7 @@ Cette alarme est absente ou non valide. Vérifiez le catalogue d’alarmes. Certaines alarmes enregistrées ne sont pas valides. Vérifiez ces entrées ; elles n’ont pas été supprimées. Impossible d’accéder à la base de données des alarmes. Réessayez. + Android n’a pas pu configurer le canal de notification de l’alarme. Réessayez. Paramètres d’alarme enregistrés Enregistré, mais impossible d’en informer la surveillance. Vérifiez son état. Les paramètres ont été enregistrés, mais les canaux de notification n’ont pas pu être mis à jour. Vérifiez les paramètres de notification Android. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 34b7a586..72bb8c82 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -330,6 +330,9 @@ एलार्म मीडिया अगर आपका डिवाइस चुनी गई वॉल्यूम श्रेणी का समर्थन करता है, तो Android उसका इस्तेमाल करता है। + मीडिया चुनने पर भी Android इस अलार्म के लिए सूचनाओं का वॉल्यूम इस्तेमाल कर सकता है। + आपने “%1$s” चुना है। Android ने इस चैनल के लिए “%2$s” ऑडियो श्रेणी दर्ज की है। + फिर कोशिश करें वॉल्यूम की श्रेणी बदलें? Android को एक नया सूचना चैनल चाहिए। Android की अनुमति होने पर ऐप आपकी ध्वनि, कंपन और महत्व की सेटिंग की कॉपी बनाता है। सूचना के अन्य विकल्प रीसेट हो सकते हैं। %1$s %2$s @@ -349,6 +352,7 @@ यह अलार्म गायब या अमान्य है। अलार्म सूची जाँचें। कुछ सहेजे गए अलार्म अमान्य हैं। इन रिकॉर्ड की जाँच करें; इन्हें हटाया नहीं गया है। अलार्म डेटाबेस तक पहुँच नहीं मिली। फिर कोशिश करें। + Android अलार्म का सूचना चैनल सेट नहीं कर सका। फिर से कोशिश करें। अलार्म सेटिंग सहेजी गई सहेजा गया, लेकिन निगरानी को सूचित नहीं किया जा सका। निगरानी की स्थिति जाँचें। सेटिंग सेव हो गई, लेकिन सूचना चैनल अपडेट नहीं हो सके। Android की सूचना सेटिंग देखें। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index e88be70b..0c3df29c 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -330,6 +330,9 @@ Riasztások Média Az Android a kiválasztott hangerőkategóriát használja, ha az eszköz támogatja. + A Média kiválasztásakor is előfordulhat, hogy az Android az értesítések hangerejét használja ehhez a riasztáshoz. + A kiválasztott hangerőkategória: „%1$s”. Az Android „%2$s” hangkategóriával regisztrálta ezt a csatornát. + Újrapróbálkozás Módosítja a hangerőkategóriát? Az Android új értesítési csatornát igényel. Az alkalmazás átmásolja a hang, a rezgés és a fontosság beállításait, amennyiben ezt az Android engedi. A többi értesítési beállítás visszaállhat az alapértékére. %1$s %2$s @@ -349,6 +352,7 @@ Ez a riasztás hiányzik vagy érvénytelen. Ellenőrizze a riasztáskatalógust. Néhány mentett riasztás érvénytelen. Ellenőrizze ezeket a bejegyzéseket; nem lettek eltávolítva. A riasztási adatbázis nem érhető el. Próbálja újra. + Az Android nem tudta beállítani a riasztás értesítési csatornáját. Próbálja újra. Riasztási beállítások mentve Mentve, de a figyelés nem értesíthető. Ellenőrizze a figyelés állapotát. A beállítások mentve, de nem sikerült frissíteni az értesítési csatornákat. Ellenőrizze az Android értesítési beállításait. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index a3fe85f1..d7df7102 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -334,6 +334,9 @@ Allarmi Contenuti multimediali Android usa la categoria del volume scelta se il dispositivo la supporta. + Anche se scegli Contenuti multimediali, Android potrebbe usare il volume delle notifiche per questo allarme. + Hai selezionato «%1$s». Android ha registrato questo canale con la categoria audio «%2$s». + Riprova Modificare la categoria del volume? Android richiede un nuovo canale di notifica. L’app copia le impostazioni di suono, vibrazione e importanza dove consentito da Android. Le altre opzioni delle notifiche potrebbero essere ripristinate. %1$s %2$s @@ -353,6 +356,7 @@ Questo allarme è mancante o non valido. Controlla il catalogo degli allarmi. Alcuni allarmi salvati non sono validi. Controlla queste voci; non sono state rimosse. Impossibile accedere al database degli allarmi. Riprova. + Android non è riuscito a configurare il canale di notifica dell’allarme. Riprova. Impostazioni allarmi salvate Salvato, ma non è stato possibile avvisare il monitoraggio. Controllane lo stato. Impostazioni salvate, ma non è stato possibile aggiornare i canali di notifica. Controlla le impostazioni delle notifiche di Android. diff --git a/app/src/main/res/values-iw/strings.xml b/app/src/main/res/values-iw/strings.xml index ea6a1511..f02f80cf 100644 --- a/app/src/main/res/values-iw/strings.xml +++ b/app/src/main/res/values-iw/strings.xml @@ -334,6 +334,9 @@ התרעות מדיה Android משתמש בקטגוריית עוצמת הקול שנבחרה אם המכשיר תומך בה. + גם בבחירה במדיה, Android עשוי להשמיע את ההתרעה בעוצמת הקול של ההתראות. + בחרת ב־%1$s. מערכת Android רשמה את הערוץ הזה בקטגוריית השמע %2$s. + ניסיון חוזר לשנות את קטגוריית עוצמת הקול? נדרש ערוץ התראות חדש ב-Android. האפליקציה תעתיק את הגדרות הצליל, הרטט והחשיבות במידה שהמערכת מאפשרת זאת. ייתכן שאפשרויות אחרות של התראות יאופסו. %1$s %2$s @@ -353,6 +356,7 @@ התרעה זו חסרה או אינה תקינה. יש לבדוק את קטלוג ההתרעות. חלק מההתרעות השמורות אינן תקינות. יש לבדוק את הרשומות האלו; הן לא הוסרו. לא ניתן לגשת למסד נתוני ההתרעות. יש לנסות שוב. + לא ניתן היה להגדיר ב-Android את ערוץ ההתראות של ההתרעה. נסו שוב. הגדרות ההתרעות נשמרו נשמר, אך לא ניתן להודיע לרכיב הניטור. יש לבדוק את מצב הניטור. ההגדרות נשמרו, אך לא ניתן היה לעדכן את ערוצי ההתראות. בדקו את הגדרות ההתראות ב-Android. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 6b824557..b4a7e10f 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -326,6 +326,9 @@ アラーム メディア 端末が対応している場合、Android は選択した種類の音量を使用します。 + メディアを選んでも、Android がこのアラームに通知の音量を使用する場合があります。 + 「%1$s」を選択しましたが、Android に登録されているこのチャンネルの音声用途は「%2$s」です。 + 再試行 音量の種類を変更しますか? Android では新しい通知チャンネルが必要です。音、バイブレーション、重要度の設定は、Android が許可する範囲で引き継がれます。その他の通知設定はリセットされる場合があります。 %1$s%2$s @@ -345,6 +348,7 @@ このアラームは存在しないか無効です。アラーム一覧を確認してください。 一部の保存済みアラームが無効です。記録を確認してください。削除はされていません。 アラームのデータベースにアクセスできませんでした。再試行してください。 + Android でアラームの通知チャンネルを設定できませんでした。もう一度お試しください。 アラーム設定を保存しました 保存しましたが、監視サービスに通知できませんでした。監視の状態を確認してください。 設定を保存しましたが、通知チャンネルを更新できませんでした。Android の通知設定を確認してください。 diff --git a/app/src/main/res/values-lt/strings.xml b/app/src/main/res/values-lt/strings.xml index 0988d393..ac9a8843 100644 --- a/app/src/main/res/values-lt/strings.xml +++ b/app/src/main/res/values-lt/strings.xml @@ -338,6 +338,9 @@ Aliarmai Medija Jei įrenginys palaiko pasirinktą garsumo kategoriją, „Android“ ją naudoja. + Net pasirinkus medijos garsumą, „Android“ šiam aliarmui gali naudoti pranešimų garsumą. + Pasirinkote „%1$s“. „Android“ šiam kanalui užregistravo garso kategoriją „%2$s“. + Bandyti dar kartą Keisti garsumo kategoriją? „Android“ reikia naujo pranešimų kanalo. Programa nukopijuos garso, vibracijos ir svarbos nustatymus, kiek tai leidžia sistema. Kitos pranešimų parinktys gali būti nustatytos iš naujo. %1$s %2$s @@ -357,6 +360,7 @@ Šio aliarmo nėra arba jis netinkamas. Peržiūrėkite aliarmų katalogą. Kai kurie išsaugoti aliarmai netinkami. Peržiūrėkite šiuos įrašus; jie nebuvo pašalinti. Nepavyko pasiekti aliarmų duomenų bazės. Bandykite dar kartą. + „Android“ nepavyko nustatyti aliarmo pranešimų kanalo. Bandykite dar kartą. Aliarmų nustatymai išsaugoti Išsaugota, bet nepavyko pranešti stebėjimo tarnybai. Patikrinkite stebėjimo būseną. Nustatymai išsaugoti, tačiau pranešimų kanalų atnaujinti nepavyko. Patikrinkite „Android“ pranešimų nustatymus. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 147f965f..c8a902ba 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -330,6 +330,9 @@ Alarmen Media Android gebruikt de gekozen volumecategorie als je apparaat deze ondersteunt. + Ook als je Media kiest, kan Android voor dit alarm het meldingsvolume gebruiken. + Je hebt ‘%1$s’ gekozen. Android heeft dit kanaal geregistreerd met de audiocategorie ‘%2$s’. + Opnieuw proberen Volumecategorie wijzigen? Android heeft een nieuw meldingskanaal nodig. De app neemt je instellingen voor geluid, trillen en prioriteit over voor zover Android dit toestaat. Andere meldingsopties kunnen worden teruggezet. %1$s %2$s @@ -349,6 +352,7 @@ Dit alarm ontbreekt of is ongeldig. Controleer het alarmoverzicht. Sommige opgeslagen alarmen zijn ongeldig. Controleer deze vermeldingen; ze zijn niet verwijderd. De alarmdatabase kon niet worden geopend. Probeer het opnieuw. + Android kon het meldingskanaal voor het alarm niet instellen. Probeer het opnieuw. Alarminstellingen opgeslagen Opgeslagen, maar de bewaking kon niet worden geïnformeerd. Controleer de bewakingsstatus. Instellingen opgeslagen, maar de meldingskanalen konden niet worden bijgewerkt. Controleer de Android-meldingsinstellingen. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 60f8cea2..ae12fbe5 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -338,6 +338,9 @@ Alarmy Multimedia Android użyje wybranej kategorii głośności, jeśli urządzenie ją obsługuje. + Android może użyć głośności powiadomień, nawet jeśli zaznaczone jest „Multimedia”. + Wybrałeś(-aś) „%1$s”. Android zarejestrował ten kanał z użyciem dźwięku „%2$s”. + Spróbuj ponownie Zmienić kategorię głośności? Android wymaga nowego kanału powiadomień. Aplikacja kopiuje Twoje ustawienia dźwięku, wibracji i ważności tam, gdzie zezwala na to Android. Inne opcje powiadomień mogą zostać zresetowane. %1$s %2$s @@ -357,6 +360,7 @@ Tego alarmu brakuje lub jest nieprawidłowy. Przejrzyj katalog alarmów. Niektóre zapisane alarmy są nieprawidłowe. Przejrzyj te wpisy; nie zostały usunięte. Nie udało się uzyskać dostępu do bazy danych alarmów. Spróbuj ponownie. + Android nie mógł skonfigurować kanału powiadomień alarmu. Spróbuj ponownie. Zapisano ustawienia alarmów Zapisano, ale nie udało się powiadomić monitora. Przejrzyj stan monitorowania. Zapisano, ale kanałów powiadomień nie udało się zaktualizować. Przejrzyj ustawienia powiadomień Androida. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index d550e7f8..56cfc9a1 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -334,6 +334,9 @@ Alarmes Mídia O Android usa a categoria de volume escolhida se o dispositivo oferecer suporte a ela. + Mesmo que você selecione Mídia, o Android pode usar o volume das notificações para este alarme. + Você selecionou “%1$s”. O Android registrou este canal com a categoria de áudio “%2$s”. + Tentar novamente Alterar a categoria de volume? O Android precisa de um novo canal de notificações. O app copia as configurações de som, vibração e importância conforme permitido pelo Android. Outras opções de notificação podem voltar ao padrão. %1$s %2$s @@ -353,6 +356,7 @@ Este alarme está em falta ou é inválido. Revise o catálogo de alarmes. Alguns alarmes salvos são inválidos. Revise estes registros; não foram removidos. Não foi possível acessar o banco de dados de alarmes. Tente novamente. + O Android não conseguiu configurar o canal de notificações do alarme. Tente novamente. Configurações de alarme salvas Salvo, mas não foi possível notificar o monitor. Revise o estado do monitoramento. As configurações foram salvas, mas não foi possível atualizar os canais de notificações. Verifique as configurações de notificações do Android. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 406c52a6..65f130a2 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -334,6 +334,9 @@ Alarmes Multimédia O Android utiliza a categoria de volume selecionada se o dispositivo a suportar. + Mesmo que selecione Multimédia, o Android pode utilizar o volume das notificações para este alarme. + Selecionou «%1$s». O Android registou este canal com a categoria de áudio «%2$s». + Tentar novamente Alterar a categoria de volume? O Android requer um novo canal de notificações. A aplicação copia as definições de som, vibração e importância na medida em que o Android o permite. Outras opções de notificação poderão voltar aos valores predefinidos. %1$s %2$s @@ -353,6 +356,7 @@ Este alarme está em falta ou é inválido. Reveja o catálogo de alarmes. Alguns alarmes guardados são inválidos. Reveja estes registos; não foram removidos. Não foi possível aceder à base de dados de alarmes. Tente novamente. + O Android não conseguiu configurar o canal de notificações do alarme. Tente novamente. Definições de alarme guardadas Guardado, mas não foi possível notificar o monitor. Reveja o estado da monitorização. As definições foram guardadas, mas não foi possível atualizar os canais de notificações. Verifique as definições de notificações do Android. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index bd21f5ab..f2b4cb9a 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -334,6 +334,9 @@ Alarme Conținut media Android folosește categoria de volum aleasă dacă dispozitivul o acceptă. + Chiar dacă selectezi Conținut media, Android poate folosi volumul notificărilor pentru această alarmă. + Ai selectat „%1$s”. Android a înregistrat acest canal cu categoria audio „%2$s”. + Reîncearcă Schimbi categoria de volum? Android necesită un canal de notificări nou. Aplicația copiază setările de sunet, vibrații și importanță în măsura în care permite Android. Celelalte opțiuni de notificare pot fi resetate. %1$s %2$s @@ -353,6 +356,7 @@ Această alarmă lipsește sau este nevalidă. Verifică lista alarmelor. Unele alarme salvate sunt nevalide. Verifică aceste înregistrări; nu au fost eliminate. Baza de date a alarmelor nu a putut fi accesată. Încearcă din nou. + Android nu a putut configura canalul de notificări al alarmei. Încearcă din nou. Setările alarmei au fost salvate Salvat, dar monitorul nu a putut fi notificat. Verifică starea monitorizării. Setările au fost salvate, dar canalele de notificări nu au putut fi actualizate. Verifică setările de notificare Android. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 1d22ca86..e32ff9cb 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -338,6 +338,9 @@ Сигналы Мультимедиа Android использует выбранную категорию громкости, если устройство её поддерживает. + Даже если выбрать «Мультимедиа», Android может воспроизвести этот сигнал с громкостью уведомлений. + Вы выбрали «%1$s». Android зарегистрировал этот канал с категорией звука «%2$s». + Повторить Изменить категорию громкости? Android требуется новый канал уведомлений. Приложение перенесёт настройки звука, вибрации и важности, если это разрешает Android. Другие настройки уведомлений могут быть сброшены. %1$s %2$s @@ -357,6 +360,7 @@ Этот сигнал отсутствует или недопустим. Проверьте каталог сигналов. Некоторые сохранённые сигналы недопустимы. Проверьте эти записи; они не были удалены. Не удалось открыть базу сигналов. Повторите попытку. + Android не удалось настроить канал уведомлений для сигнала. Попробуйте ещё раз. Настройки сигналов сохранены Сохранено, но не удалось уведомить мониторинг. Проверьте состояние мониторинга. Настройки сохранены, но обновить каналы уведомлений не удалось. Проверьте настройки уведомлений Android. diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 12a55f3c..ed2abd67 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -338,6 +338,9 @@ Alarmy Médiá Android použije vybranú kategóriu hlasitosti, ak ju zariadenie podporuje. + Aj pri výbere médií môže Android pre tento alarm použiť hlasitosť oznámení. + Vybrali ste kategóriu hlasitosti „%1$s“. Android zaregistroval tento kanál s kategóriou zvuku „%2$s“. + Skúsiť znova Zmeniť kategóriu hlasitosti? Android vyžaduje nový kanál upozornení. Aplikácia skopíruje nastavenia zvuku, vibrácií a dôležitosti v rozsahu, ktorý Android umožňuje. Ostatné možnosti upozornení sa môžu obnoviť na predvolené hodnoty. %1$s %2$s @@ -357,6 +360,7 @@ Tento alarm chýba alebo je neplatný. Skontrolujte katalóg alarmov. Niektoré uložené alarmy sú neplatné. Skontrolujte tieto záznamy; neboli odstránené. Nemožno pristúpiť k databáze alarmov. Skúste to znova. + Androidu sa nepodarilo nastaviť kanál oznámení pre alarm. Skúste to znova. Nastavenia alarmov uložené Uložené, ale monitorovanie sa nepodarilo upozorniť. Skontrolujte stav monitorovania. Uložené, ale kanály upozornení sa nepodarilo aktualizovať. Skontrolujte nastavenia upozornení Androidu. diff --git a/app/src/main/res/values-sl/strings.xml b/app/src/main/res/values-sl/strings.xml index b0abb68a..c211357b 100644 --- a/app/src/main/res/values-sl/strings.xml +++ b/app/src/main/res/values-sl/strings.xml @@ -338,6 +338,9 @@ Alarmi Predstavnost Android uporabi izbrano kategorijo glasnosti, če jo naprava podpira. + Tudi če izberete predstavnost, lahko Android ta alarm predvaja z glasnostjo obvestil. + Izbrali ste »%1$s«. Android je ta kanal registriral z zvočno kategorijo »%2$s«. + Poskusi znova Želite spremeniti kategorijo glasnosti? Android zahteva nov kanal obvestil. Aplikacija kopira nastavitve zvoka, vibriranja in pomembnosti, kolikor to dovoljuje Android. Druge možnosti obvestil se lahko ponastavijo. %1$s %2$s @@ -357,6 +360,7 @@ Ta alarm manjka ali je neveljaven. Preglejte katalog alarmov. Nekateri shranjeni alarmi so neveljavni. Preglejte te zapise; niso bili odstranjeni. Do zbirke alarmov ni bilo mogoče dostopati. Poskusite znova. + Android ni mogel nastaviti kanala obvestil za alarm. Poskusite znova. Nastavitve alarmov shranjene Shranjeno, vendar spremljanja ni bilo mogoče obvestiti. Preverite stanje spremljanja. Nastavitve so shranjene, vendar kanalov obvestil ni bilo mogoče posodobiti. Preverite nastavitve obvestil za Android. diff --git a/app/src/main/res/values-sr/strings.xml b/app/src/main/res/values-sr/strings.xml index 72016bc8..e8650869 100644 --- a/app/src/main/res/values-sr/strings.xml +++ b/app/src/main/res/values-sr/strings.xml @@ -334,6 +334,9 @@ Alarmi Mediji Android koristi izabranu kategoriju jačine zvuka ako je uređaj podržava. + Čak i ako izaberete Mediji, Android može da koristi jačinu zvuka obaveštenja za ovaj alarm. + Izabrali ste „%1$s“. Android je registrovao ovaj kanal sa kategorijom zvuka „%2$s“. + Pokušaj ponovo Promeniti kategoriju jačine zvuka? Android zahteva novi kanal za obaveštenja. Aplikacija kopira podešavanja zvuka, vibracije i važnosti u meri u kojoj Android to dozvoljava. Ostale opcije obaveštenja mogu se vratiti na podrazumevane vrednosti. %1$s %2$s @@ -353,6 +356,7 @@ Ovaj alarm nedostaje ili nije važeći. Pregledajte katalog alarma. Neki sačuvani alarmi nisu važeći. Pregledajte ove zapise; nisu uklonjeni. Pristup bazi alarma nije moguć. Pokušajte ponovo. + Android nije uspeo da podesi kanal za obaveštenja alarma. Pokušajte ponovo. Podešavanja alarma sačuvana Sačuvano, ali praćenje nije moglo biti obavešteno. Proverite stanje praćenja. Podešavanja su sačuvana, ali nije bilo moguće ažurirati kanale za obaveštenja. Proverite Android podešavanja obaveštenja. diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 6595e5b7..4003d543 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -330,6 +330,9 @@ Alarmlar Medya Cihazınız destekliyorsa Android seçilen ses düzeyi kategorisini kullanır. + Medya seçili olsa bile Android bu alarm için bildirim ses düzeyini kullanabilir. + “%1$s” seçtiniz. Android bu kanalı “%2$s” ses kategorisiyle kaydetti. + Yeniden dene Ses düzeyi kategorisi değiştirilsin mi? Android yeni bir bildirim kanalı gerektirir. Uygulama, Android’in izin verdiği ölçüde ses, titreşim ve önem ayarlarını kopyalar. Diğer bildirim seçenekleri sıfırlanabilir. %1$s %2$s @@ -349,6 +352,7 @@ Bu alarm eksik veya geçersiz. Alarm kataloğunu gözden geçirin. Kaydedilen bazı alarmlar geçersiz. Bu kayıtları gözden geçirin; kaldırılmadılar. Alarm veritabanına erişilemedi. Yeniden deneyin. + Android alarm bildirim kanalını ayarlayamadı. Tekrar deneyin. Alarm ayarları kaydedildi Kaydedildi ancak izleme hizmetine bildirilemedi. İzleme durumunu gözden geçirin. Ayarlar kaydedildi ancak bildirim kanalları güncellenemedi. Android bildirim ayarlarını kontrol edin. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index e1afb34f..6057bf23 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -326,6 +326,9 @@ 警报 媒体 如果设备支持,Android 会使用所选的音量类别。 + 即使选择“媒体”,Android 仍可能使用通知音量播放此警报。 + 你选择了“%1$s”。Android 为此渠道注册的音频用途为“%2$s”。 + 重试 要更改音量类别吗? Android 需要新的通知渠道。应用会在 Android 允许的范围内复制声音、振动和重要程度设置。其他通知选项可能会重置。 %1$s%2$s @@ -345,6 +348,7 @@ 此警报遗失或无效。请检查警报列表。 部分保存的警报无效。请检查这些记录;它们尚未被移除。 无法访问警报数据库。请再试一次。 + Android 无法设置警报的通知渠道。请重试。 警报设置已保存 已保存,但无法通知监测服务。请检查监测状态。 设置已保存,但无法更新通知渠道。请检查 Android 通知设置。 diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index fc1f8f1c..33ca8648 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -326,6 +326,9 @@ 警報 媒體 如果裝置支援,Android 會使用所選的音量類別。 + 即使選擇「媒體」,Android 仍可能以通知音量播放此警報。 + 您選擇了「%1$s」。Android 為此頻道登錄的音訊用途為「%2$s」。 + 重試 要變更音量類別嗎? Android 需要建立新的通知頻道。應用程式會在 Android 允許的範圍內複製音效、震動和重要性設定。其他通知選項可能會重設。 %1$s%2$s @@ -345,6 +348,7 @@ 此警報遺失或無效。請檢查警報清單。 部分儲存的警報無效。請檢查這些記錄;它們尚未被移除。 無法存取警報資料庫。請再試一次。 + Android 無法設定警報的通知頻道。請再試一次。 警報設定已儲存 已儲存,但無法通知監測服務。請檢查監測狀態。 設定已儲存,但無法更新通知頻道。請檢查 Android 通知設定。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index bc241a92..c483cf77 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -330,6 +330,9 @@ Alarms Media Android uses the requested volume category when supported by your device. + Android may use notification volume even when Media is selected. + You selected %1$s. Android registered this channel with %2$s audio usage. + Retry Change audio volume category? Android requires a new notification channel. The app copies your sound, vibration, and importance settings where Android allows. Other notification options may reset. %1$s %2$s @@ -349,6 +352,7 @@ This alarm is missing or invalid. Review the alarm catalog. Some saved alarms are invalid. Review these records; they have not been removed. Could not access the alarm database. Try again. + Android could not set up the alarm notification channel. Try again. Alarm settings saved Saved, but the monitor could not be notified. Review monitoring status. Saved, but notification channels could not be updated. Review Android notification settings. diff --git a/app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt b/app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt index 750af85f..93484286 100644 --- a/app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt +++ b/app/src/test/kotlin/codes/swistak/batterymonitor/alarms/backup/AlarmChannelRestoreTest.kt @@ -9,6 +9,7 @@ import codes.swistak.batterymonitor.alarms.AlarmDatabase import codes.swistak.batterymonitor.alarms.AlarmSoundSettings import codes.swistak.batterymonitor.alarms.AlarmVolumeCategory import codes.swistak.batterymonitor.alarms.projectAlarms +import codes.swistak.batterymonitor.monitoring.notifications.AlarmChannelRegistrationException import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -88,6 +89,13 @@ class AlarmChannelRestoreTest { database.saveCustomSettings( alarm, null, AlarmConfiguration(settings, missingId) ) + val recoveredId = "alarm_settings_existing_shared" + database.saveSharedSettings( + "fully_charged", null, AlarmConfiguration(channelId = recoveredId) + ) + shadow.rememberedChannel = NotificationChannel( + recoveredId, "Independent shared alarm", NotificationManager.IMPORTANCE_LOW + ) manager.createNotificationChannel( NotificationChannel( type, type, NotificationManager.IMPORTANCE_NONE @@ -100,11 +108,17 @@ class AlarmChannelRestoreTest { }""" shadow.rejectId = missingId - assertThrows(IllegalStateException::class.java) { + assertThrows(AlarmChannelRegistrationException::class.java) { AlarmBackup.importFromJson(context, database, backup, allowChannelChanges = true) } assertEquals(before, database.getSnapshot()) - assertEquals(listOf(type), manager.notificationChannels.map { it.id }) + assertEquals( + setOf(type, recoveredId), manager.notificationChannels.map { it.id }.toSet() + ) + assertEquals( + NotificationManager.IMPORTANCE_LOW, + manager.getNotificationChannel(recoveredId).importance + ) shadow.rejectId = null AlarmBackup.importFromJson( diff --git a/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt b/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt index d6af7921..71182203 100644 --- a/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt +++ b/app/src/test/kotlin/codes/swistak/batterymonitor/monitoring/notifications/NotificationChannelsTest.kt @@ -22,6 +22,7 @@ import android.app.NotificationChannelGroup import android.app.NotificationManager import android.content.Context import android.content.res.Configuration +import android.database.sqlite.SQLiteException import android.media.AudioAttributes import android.media.RingtoneManager import android.net.Uri @@ -660,7 +661,7 @@ class NotificationChannelsTest { } })) { shadow.interceptRegistration = register - assertThrows(IllegalStateException::class.java) { + assertThrows(AlarmChannelRegistrationException::class.java) { NotificationChannels.saveAlarmSettings( context, database, type, null, null, requested, true ) @@ -675,6 +676,200 @@ class NotificationChannelsTest { } } + @Test + fun `an existing notification event channel satisfies a request for notification volume`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CHARGED + val tone = Uri.parse("content://test/notification-tone") + val prior = + AlarmConfiguration(AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.MEDIA)) + database.saveSharedSettings(type, null, prior) + val eventUsage = + AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT) + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build() + manager.createNotificationChannel( + NotificationChannel(type, type, NotificationManager.IMPORTANCE_HIGH).apply { + setSound(tone, eventUsage) + }) + val preference = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.NOTIFICATIONS) + val saved = NotificationChannels.saveAlarmSettings( + context, database, type, null, prior, preference, replacementConfirmed = false + ) + assertNull(saved.usageMismatch) + assertEquals(preference, database.getSnapshot().effective(type).sound) + assertEquals(listOf(type), manager.notificationChannels.map { it.id }) + assertEquals(eventUsage, manager.getNotificationChannel(type).audioAttributes) + } + + @Test + fun `silent and low importance channels do not need an audio stream repair`() { + val category = AlarmVolumeCategory.ALARMS + val silent = NotificationChannel( + "silent", "Silent", NotificationManager.IMPORTANCE_HIGH + ).apply { setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT) } + val quiet = + NotificationChannel("quiet", "Quiet", NotificationManager.IMPORTANCE_LOW).apply { + setSound( + Uri.parse("content://test/tone"), Notification.AUDIO_ATTRIBUTES_DEFAULT + ) + } + assertNull(NotificationChannels.audioUsageMismatch(category, silent)) + assertNull(NotificationChannels.audioUsageMismatch(category, quiet)) + } + + @Test + fun `failed settings write reports the database error and removes the newly registered channel`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CHARGED + manager.createNotificationChannel( + NotificationChannel( + type, type, NotificationManager.IMPORTANCE_HIGH + ) + ) + context.openOrCreateDatabase("alarms.db", Context.MODE_PRIVATE, null).use { + it.execSQL( + "CREATE TRIGGER reject_settings BEFORE INSERT ON alarm_sound_settings " + "BEGIN SELECT RAISE(ABORT, 'injected write failure'); END" + ) + } + assertThrows(SQLiteException::class.java) { + NotificationChannels.saveAlarmSettings( + context, + database, + type, + null, + null, + AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS), + replacementConfirmed = true + ) + } + assertEquals(AlarmConfiguration(), database.getSnapshot().effective(type)) + assertEquals(listOf(type), manager.notificationChannels.map { it.id }) + } + + @Test + fun `coerced audio usage preserves the preference and only a successful explicit retry switches channels`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CHARGED + val tone = Uri.parse("content://test/selected-tone") + manager.createNotificationChannel( + NotificationChannel(type, type, NotificationManager.IMPORTANCE_HIGH).apply { + setSound(tone, Notification.AUDIO_ATTRIBUTES_DEFAULT) + setShowBadge(false) + }) + val attempts = mutableListOf() + shadow.interceptRegistration = { channel -> + if (channel.id.startsWith("alarm_settings_")) { + attempts += channel.id + channel.setSound(channel.sound, Notification.AUDIO_ATTRIBUTES_DEFAULT) + } + channel + } + val preference = AlarmSoundSettings(volumeCategory = AlarmVolumeCategory.ALARMS) + val saved = NotificationChannels.saveAlarmSettings( + context, database, type, null, null, preference, replacementConfirmed = true + ) + val mismatch = requireNotNull(saved.usageMismatch) + assertEquals(AlarmVolumeCategory.ALARMS, mismatch.requested) + assertEquals(AudioAttributes.USAGE_NOTIFICATION, mismatch.registeredUsage) + val current = database.getSnapshot().shared.getValue(type) + val originalId = requireNotNull(current.channelId) + assertEquals(preference, current.sound) + + NotificationChannels.syncAlarmChannels(context) + fun save(repair: Boolean) = NotificationChannels.saveAlarmSettings( + context, + database, + type, + null, + database.getSnapshot().shared.getValue(type), + preference, + replacementConfirmed = repair, + repairChannel = repair + ) + assertEquals(mismatch, save(repair = false).usageMismatch) + assertEquals(listOf(originalId), attempts) + assertEquals(mismatch, save(repair = true).usageMismatch) + assertEquals(current, database.getSnapshot().shared[type]) + assertEquals(2, attempts.size) + assertNull(manager.getNotificationChannel(attempts.last())) + + shadow.interceptRegistration = { it } + assertNull(save(repair = true).usageMismatch) + val repaired = database.getSnapshot().shared.getValue(type) + val repairedId = requireNotNull(repaired.channelId) + assertNotEquals(originalId, repairedId) + assertNull(manager.getNotificationChannel(originalId)) + val registered = requireNotNull(manager.getNotificationChannel(repairedId)) + assertEquals(AudioAttributes.USAGE_ALARM, registered.audioAttributes.usage) + assertEquals(tone, registered.sound) + assertFalse(registered.canShowBadge()) + + // The channel may already match by the time a second retry acquires the lock. + val updates = shadow.channelUpdates + assertNull(save(repair = true).usageMismatch) + assertEquals(updates, shadow.channelUpdates) + assertEquals(repaired, database.getSnapshot().shared[type]) + } + + @Test + fun `a failed recovery allows an independently audible threshold to recover under a blocked silent parent`() = + withDatabase { database -> + val type = NotificationChannels.CHAN_ID_A_CDROP + val missing = "alarm_settings_unavailable" + database.saveSharedSettings( + NotificationChannels.CHAN_ID_A_CHARGED, + null, + AlarmConfiguration(channelId = missing) + ) + manager.createNotificationChannel( + NotificationChannel( + type, type, NotificationManager.IMPORTANCE_NONE + ).apply { setSound(null, null) }) + database.saveThreshold(type, "23", emptyList()) + val alarm = + projectAlarms(database.getAlarmRules()).types.single { it.definition.type == type }.alarms.single() + val rememberedId = "alarm_settings_dedicated" + val saved = AlarmConfiguration(channelId = rememberedId) + database.saveCustomSettings(alarm, null, saved) + val tone = Uri.parse("content://test/independent-threshold-tone") + val remembered = NotificationChannel( + rememberedId, "Custom", NotificationManager.IMPORTANCE_HIGH + ).apply { + setSound(tone, Notification.AUDIO_ATTRIBUTES_DEFAULT) + } + shadow.interceptRegistration = { channel -> + when (channel.id) { + missing -> null + rememberedId -> remembered + else -> channel + } + } + + assertFalse(NotificationChannels.syncAlarmChannels(context)) + val recovered = requireNotNull(manager.getNotificationChannel(rememberedId)) + assertEquals(tone, recovered.sound) + assertEquals(NotificationManager.IMPORTANCE_HIGH, recovered.importance) + assertEquals(saved, database.getSnapshot().custom[alarm.id]) + assertNull(manager.getNotificationChannel(missing)) + assertEquals( + NotificationManager.IMPORTANCE_NONE, manager.getNotificationChannel(type).importance + ) + assertNull(manager.getNotificationChannel(type).sound) + assertEquals( + rememberedId, NotificationChannels.ensureAlarmChannel(context, type, alarm.id) + ) + assertThrows(AlarmChannelRegistrationException::class.java) { + NotificationChannels.ensureAlarmChannel( + context, NotificationChannels.CHAN_ID_A_CHARGED + ) + } + + shadow.interceptRegistration = { it } + assertTrue(NotificationChannels.syncAlarmChannels(context)) + assertEquals(missing, manager.getNotificationChannel(missing).id) + assertEquals(tone, manager.getNotificationChannel(rememberedId).sound) + } + private fun withDatabase(test: (AlarmDatabase) -> Unit) { val database = AlarmDatabase(context) try { From 073e238beb1aa4ec839f8cf9b6be49ee63753c82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=9Awistak?= <9076255+tswistak@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:49:36 +0100 Subject: [PATCH 3/6] Update app/src/main/res/values-pl/strings.xml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Agnieszka C <85929121+Aga-C@users.noreply.github.com> Signed-off-by: Tomasz Świstak <9076255+tswistak@users.noreply.github.com> --- app/src/main/res/values-pl/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index ae12fbe5..126d8c50 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -338,7 +338,7 @@ Alarmy Multimedia Android użyje wybranej kategorii głośności, jeśli urządzenie ją obsługuje. - Android może użyć głośności powiadomień, nawet jeśli zaznaczone jest „Multimedia”. + Android może użyć głośności powiadomień nawet wtedy, gdy wybrane jest „Multimedia”. Wybrałeś(-aś) „%1$s”. Android zarejestrował ten kanał z użyciem dźwięku „%2$s”. Spróbuj ponownie Zmienić kategorię głośności? From 3119ac3635aad0178f5ec0b7055660bf821ce5f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=9Awistak?= <9076255+tswistak@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:49:42 +0100 Subject: [PATCH 4/6] Update app/src/main/res/values-pl/strings.xml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Agnieszka C <85929121+Aga-C@users.noreply.github.com> Signed-off-by: Tomasz Świstak <9076255+tswistak@users.noreply.github.com> --- app/src/main/res/values-pl/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 126d8c50..8458f421 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -360,7 +360,7 @@ Tego alarmu brakuje lub jest nieprawidłowy. Przejrzyj katalog alarmów. Niektóre zapisane alarmy są nieprawidłowe. Przejrzyj te wpisy; nie zostały usunięte. Nie udało się uzyskać dostępu do bazy danych alarmów. Spróbuj ponownie. - Android nie mógł skonfigurować kanału powiadomień alarmu. Spróbuj ponownie. + Android nie mógł ustawić kanału powiadomień alarmów. Spróbuj ponownie. Zapisano ustawienia alarmów Zapisano, ale nie udało się powiadomić monitora. Przejrzyj stan monitorowania. Zapisano, ale kanałów powiadomień nie udało się zaktualizować. Przejrzyj ustawienia powiadomień Androida. From d739af04c1c2e3f8b6a519e62cb378fe241a259e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20=C5=9Awistak?= <9076255+tswistak@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:49:50 +0100 Subject: [PATCH 5/6] Update app/src/main/res/values-pl/strings.xml MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Agnieszka C <85929121+Aga-C@users.noreply.github.com> Signed-off-by: Tomasz Świstak <9076255+tswistak@users.noreply.github.com> --- app/src/main/res/values-pl/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 8458f421..1eacdf5d 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -340,7 +340,7 @@ Android użyje wybranej kategorii głośności, jeśli urządzenie ją obsługuje. Android może użyć głośności powiadomień nawet wtedy, gdy wybrane jest „Multimedia”. Wybrałeś(-aś) „%1$s”. Android zarejestrował ten kanał z użyciem dźwięku „%2$s”. - Spróbuj ponownie + Ponów Zmienić kategorię głośności? Android wymaga nowego kanału powiadomień. Aplikacja kopiuje Twoje ustawienia dźwięku, wibracji i ważności tam, gdzie zezwala na to Android. Inne opcje powiadomień mogą zostać zresetowane. %1$s %2$s From 70f1fbb060e75b18c6dc02923d2fcad60120659d Mon Sep 17 00:00:00 2001 From: Tomasz Swistak Date: Mon, 30 Nov 2026 09:52:30 +0100 Subject: [PATCH 6/6] prettify strings --- app/src/main/res/values/strings.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c483cf77..11c56877 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -330,8 +330,8 @@ Alarms Media Android uses the requested volume category when supported by your device. - Android may use notification volume even when Media is selected. - You selected %1$s. Android registered this channel with %2$s audio usage. + Android may use notification volume even when “Media” is selected. + You selected “%1$s”. Android registered this channel with “%2$s” audio usage. Retry Change audio volume category? Android requires a new notification channel. The app copies your sound, vibration, and importance settings where Android allows. Other notification options may reset.