Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Improved

- Notification audio channel change reliability.

### Fixed

- Support for monochrome system color palette (#199).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,24 @@
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.media.RingtoneManager
import android.net.Uri
import android.os.Bundle
import androidx.lifecycle.SavedStateHandle
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.AlarmChannelSaveAction
import codes.swistak.batterymonitor.ui.alarms.AlarmDraft
import codes.swistak.batterymonitor.ui.alarms.AlarmsState
import codes.swistak.batterymonitor.ui.alarms.AlarmsViewModel
Expand All @@ -40,10 +46,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 {
Expand Down Expand Up @@ -90,6 +98,98 @@ class AlarmDatabaseInstrumentedTest {
).use { it.execSQL(statement) }
}

private fun assumeIsolatedChannels(manager: NotificationManager) {
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:"
))
}
)
}

@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",
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())
Expand Down Expand Up @@ -247,13 +347,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<Any>(
row.id,
if (row.enabled) 1 else 0,
row.type,
row.threshold,
id,
if (enabled) 1 else 0,
type,
threshold,
"content://saved/tone"
)
)
Expand Down Expand Up @@ -478,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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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))
Expand All @@ -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)
)
Expand All @@ -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",
Expand Down Expand Up @@ -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
Expand All @@ -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))
Expand Down Expand Up @@ -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)
}
Expand All @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
)
)
)
Expand All @@ -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()
)
})
}
}

Expand All @@ -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)
Expand Down
Loading
Loading