watch: add bidirectional Do-Not-Disturb sync over a new BLE characteristic
- Commit
95630b71e54378c3af1dedf80c275abc61259fcb- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-06 17:46 UTC (5 months ago)
- Parents
04ff8d9
Diff
watch/phone/src/main/AndroidManifest.xml
diff --git a/watch/phone/src/main/AndroidManifest.xml b/watch/phone/src/main/AndroidManifest.xmlindex 265e07163b..84b2c718cc 100644--- a/watch/phone/src/main/AndroidManifest.xml+++ b/watch/phone/src/main/AndroidManifest.xml@@ -11,6 +11,7 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" /> <!-- Health Connect --> <uses-permission android:name="android.permission.health.WRITE_HEART_RATE" />
watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.ktindex 49a22f979a..ac1c1e9224 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/MainActivity.kt@@ -1,10 +1,12 @@ package com.vayunmathur.watch.phone import android.Manifest+import android.app.NotificationManager import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle+import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent@@ -50,6 +52,9 @@ class MainActivity : ComponentActivity() { private fun SyncScreen(modifier: Modifier) { val context = this val health = remember { HealthConnectManager(context) }+ val notificationManager = remember {+ context.getSystemService(NotificationManager::class.java)+ } val connection by SyncForegroundService.connectionStateFlow.collectAsState() val synced by SyncForegroundService.syncedCountFlow.collectAsState()@@ -57,6 +62,7 @@ class MainActivity : ComponentActivity() { var hasBlePerms by remember { mutableStateOf(false) } var hasHcPerms by remember { mutableStateOf(false) } var hcAvailable by remember { mutableStateOf(true) }+ var hasDndAccess by remember { mutableStateOf(true) } val blePermsLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestMultiplePermissions(),@@ -74,6 +80,7 @@ class MainActivity : ComponentActivity() { } hcAvailable = health.isAvailable() if (hcAvailable) hasHcPerms = health.hasAllPermissions()+ hasDndAccess = notificationManager.isNotificationPolicyAccessGranted } Column(@@ -103,6 +110,14 @@ class MainActivity : ComponentActivity() { } } }++ // Policy access can't be granted via the runtime permission dialog, so+ // deep-link into the dedicated Settings screen when it is missing.+ if (!hasDndAccess) {+ Button(onClick = { openDndAccessSettings() }) {+ Text(stringResource(R.string.grant_dnd_access))+ }+ } } } @@ -121,6 +136,14 @@ class MainActivity : ComponentActivity() { Manifest.permission.POST_NOTIFICATIONS, ) + private fun openDndAccessSettings() {+ try {+ startActivity(Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS))+ } catch (e: Exception) {+ startActivity(Intent(Settings.ACTION_SETTINGS))+ }+ }+ private fun openHealthConnectInstall() { val uri = Uri.parse("market://details?id=com.google.android.apps.healthdata") try {
watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.ktindex 21d3ae3e2c..a76e9a64cf 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/ble/GattClientManager.kt@@ -48,6 +48,7 @@ class GattClientManager(private val context: Context) { private var gatt: BluetoothGatt? = null private var scanning = false+ private var dndCharacteristic: BluetoothGattCharacteristic? = null private val reassembly = ByteArrayOutputStream() @@ -57,6 +58,10 @@ class GattClientManager(private val context: Context) { private val _batches = MutableSharedFlow<List<WatchRecord>>(extraBufferCapacity = 8) val batches: SharedFlow<List<WatchRecord>> = _batches + // Interruption-filter bytes pushed by the watch over the DND characteristic.+ private val _remoteDnd = MutableSharedFlow<Int>(extraBufferCapacity = 8)+ val remoteDnd: SharedFlow<Int> = _remoteDnd+ fun startScan() { val scanner = bluetoothManager.adapter?.bluetoothLeScanner ?: return if (scanning) return@@ -123,7 +128,10 @@ class GattClientManager(private val context: Context) { if (status != BluetoothGatt.GATT_SUCCESS) return val service = gatt.getService(BleConstants.SERVICE_UUID) ?: return val dataChar = service.getCharacteristic(BleConstants.DATA_CHARACTERISTIC_UUID) ?: return+ dndCharacteristic = service.getCharacteristic(BleConstants.DND_CHARACTERISTIC_UUID) _state.value = ConnectionState.Connected+ // Enable the Data CCCD first; the DND CCCD is enabled from+ // onDescriptorWrite so the two descriptor writes are sequenced. subscribe(gatt, dataChar) } @@ -132,8 +140,14 @@ class GattClientManager(private val context: Context) { descriptor: BluetoothGattDescriptor, status: Int, ) {- // Subscription active; the watch will now push the batch.- reassembly.reset()+ when (descriptor.characteristic?.uuid) {+ BleConstants.DATA_CHARACTERISTIC_UUID -> {+ // Subscription active; the watch will now push the batch.+ reassembly.reset()+ // Then subscribe to DND (one GATT op at a time).+ dndCharacteristic?.let { subscribe(gatt, it) }+ }+ } } override fun onCharacteristicChanged(@@ -141,11 +155,17 @@ class GattClientManager(private val context: Context) { characteristic: BluetoothGattCharacteristic, value: ByteArray, ) {- if (characteristic.uuid != BleConstants.DATA_CHARACTERISTIC_UUID) return- if (value.contentEquals(BleConstants.EOT_MARKER)) {- finishBatch(gatt)- } else {- reassembly.write(value)+ when (characteristic.uuid) {+ BleConstants.DATA_CHARACTERISTIC_UUID -> {+ if (value.contentEquals(BleConstants.EOT_MARKER)) {+ finishBatch(gatt)+ } else {+ reassembly.write(value)+ }+ }+ BleConstants.DND_CHARACTERISTIC_UUID -> {+ if (value.isNotEmpty()) _remoteDnd.tryEmit(value[0].toInt())+ } } } }@@ -156,6 +176,18 @@ class GattClientManager(private val context: Context) { gatt.writeDescriptor(cccd, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) } + /** Writes a new interruption filter to the watch's DND characteristic. */+ fun writeDnd(filter: Int) {+ val g = gatt ?: return+ val service = g.getService(BleConstants.SERVICE_UUID) ?: return+ val dnd = service.getCharacteristic(BleConstants.DND_CHARACTERISTIC_UUID) ?: return+ g.writeCharacteristic(+ dnd,+ byteArrayOf(filter.toByte()),+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,+ )+ }+ private fun finishBatch(gatt: BluetoothGatt) { val bytes = reassembly.toByteArray() reassembly.reset()
watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/DndController.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/DndController.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/DndController.ktnew file mode 100644index 0000000000..dacec7e96f--- /dev/null+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/DndController.kt@@ -0,0 +1,70 @@+package com.vayunmathur.watch.phone.sync++import android.app.NotificationManager+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import com.vayunmathur.watch.phone.ble.GattClientManager+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.launch++/**+ * Phone-side counterpart to the watch's DndController: mirrors the notification+ * interruption filter across the BLE link. Local changes are written to the+ * watch's DND characteristic; remote changes (collected from+ * [GattClientManager.remoteDnd]) are applied here. Same last-change-wins loop+ * guard: a filter we applied ourselves is not echoed back.+ */+class DndController(+ context: Context,+ private val client: GattClientManager,+) {+ private val appContext = context.applicationContext+ private val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager++ @Volatile private var lastAppliedFilter = -1+ private var registered = false++ private val receiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context?, intent: Intent?) {+ if (intent?.action == NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED) {+ onLocalChanged()+ }+ }+ }++ fun register(scope: CoroutineScope) {+ if (registered) return+ appContext.registerReceiver(+ receiver,+ IntentFilter(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED),+ )+ registered = true+ scope.launch {+ client.remoteDnd.collect { applyRemote(it) }+ }+ }++ fun unregister() {+ if (!registered) return+ runCatching { appContext.unregisterReceiver(receiver) }+ registered = false+ }++ private fun applyRemote(filter: Int) {+ if (!nm.isNotificationPolicyAccessGranted) return+ if (filter == nm.currentInterruptionFilter) return+ lastAppliedFilter = filter+ runCatching { nm.setInterruptionFilter(filter) }+ }++ private fun onLocalChanged() {+ val filter = nm.currentInterruptionFilter+ if (filter == lastAppliedFilter) {+ lastAppliedFilter = -1+ return+ }+ client.writeDnd(filter)+ }+}
watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt
diff --git a/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.ktindex 5a1b269671..e39dd1f5d4 100644--- a/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt+++ b/watch/phone/src/main/java/com/vayunmathur/watch/phone/sync/SyncForegroundService.kt@@ -35,6 +35,7 @@ class SyncForegroundService : Service() { private lateinit var client: GattClientManager private lateinit var health: HealthConnectManager private lateinit var buffer: ReceivedDatabase+ private lateinit var dndController: DndController private val derivations = HealthDerivations() override fun onCreate() {@@ -42,6 +43,8 @@ class SyncForegroundService : Service() { client = GattClientManager(this) health = HealthConnectManager(this) buffer = ReceivedDatabase.get(this)+ dndController = DndController(this, client)+ dndController.register(scope) scope.launch { client.state.collect { state ->@@ -113,6 +116,7 @@ class SyncForegroundService : Service() { override fun onDestroy() { client.disconnect()+ dndController.unregister() scope.cancel() connectionState.value = ConnectionState.Disconnected super.onDestroy()
watch/phone/src/main/res/values/strings.xml
diff --git a/watch/phone/src/main/res/values/strings.xml b/watch/phone/src/main/res/values/strings.xmlindex 7cee3744a4..6b4a830f12 100644--- a/watch/phone/src/main/res/values/strings.xml+++ b/watch/phone/src/main/res/values/strings.xml@@ -16,4 +16,5 @@ <string name="notification_channel_name">Watch Sync</string> <string name="notification_title">Syncing watch health data</string> <string name="notification_text">Maintaining BLE link and writing to Health Connect</string>+ <string name="grant_dnd_access">Grant Do Not Disturb Access</string> </resources>
watch/watch/src/main/AndroidManifest.xml
diff --git a/watch/watch/src/main/AndroidManifest.xml b/watch/watch/src/main/AndroidManifest.xmlindex f5cbce3d83..ab2c0b3069 100644--- a/watch/watch/src/main/AndroidManifest.xml+++ b/watch/watch/src/main/AndroidManifest.xml@@ -21,6 +21,7 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.WAKE_LOCK" />+ <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" /> <application android:allowBackup="true"
watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.ktindex fc3bbb80d3..5727f178b1 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/MainActivity.kt@@ -1,9 +1,11 @@ package com.vayunmathur.watch.watch import android.Manifest+import android.app.NotificationManager import android.content.Intent import android.os.Build import android.os.Bundle+import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent@@ -183,6 +185,28 @@ class MainActivity : ComponentActivity() { Button(onClick = onOpenPicker, modifier = Modifier.padding(top = 8.dp)) { Text(stringResource(R.string.exercise_start_workout)) }++ val notificationManager = remember {+ context.getSystemService(NotificationManager::class.java)+ }+ var hasDndAccess by remember {+ mutableStateOf(notificationManager.isNotificationPolicyAccessGranted)+ }+ if (!hasDndAccess) {+ Button(+ onClick = {+ runCatching {+ context.startActivity(+ Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS),+ )+ }+ hasDndAccess = notificationManager.isNotificationPolicyAccessGranted+ },+ modifier = Modifier.padding(top = 8.dp),+ ) {+ Text(stringResource(R.string.grant_dnd_access))+ }+ } } }
watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.ktindex 46cdd0f261..d91e5e9714 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/ble/GattServerManager.kt@@ -53,6 +53,9 @@ class GattServerManager( private val context: Context, private val dao: SensorDao, private val scope: CoroutineScope,+ // Invoked when the phone writes a new interruption filter to the DND+ // characteristic. The caller (DndController) applies it locally, loop-guarded.+ private val onRemoteDnd: (Int) -> Unit = {}, ) { private val json = Json { ignoreUnknownKeys = true } @@ -64,6 +67,7 @@ class GattServerManager( private lateinit var dataCharacteristic: BluetoothGattCharacteristic private lateinit var controlCharacteristic: BluetoothGattCharacteristic+ private lateinit var dndCharacteristic: BluetoothGattCharacteristic // Per-device negotiated MTU (default 23 until MTU exchange). private val deviceMtu = mutableMapOf<String, Int>()@@ -71,6 +75,13 @@ class GattServerManager( // Ids streamed to each device in the last batch, pending ACK. private val pendingAck = mutableMapOf<String, List<Long>>() + // Devices subscribed to DND notifications, keyed by address.+ private val dndSubscribers = mutableMapOf<String, BluetoothDevice>()++ // Authoritative interruption-filter byte the watch holds and serves. Defaults+ // to ALL (1 = no Do-Not-Disturb) until the local DndController pushes reality.+ @Volatile private var currentDnd: Int = 1+ private val _advertising = MutableStateFlow(false) val advertising: StateFlow<Boolean> = _advertising @@ -122,8 +133,23 @@ class GattServerManager( BluetoothGattCharacteristic.PERMISSION_WRITE, ) + dndCharacteristic = BluetoothGattCharacteristic(+ BleConstants.DND_CHARACTERISTIC_UUID,+ BluetoothGattCharacteristic.PROPERTY_READ or+ BluetoothGattCharacteristic.PROPERTY_WRITE or+ BluetoothGattCharacteristic.PROPERTY_NOTIFY,+ BluetoothGattCharacteristic.PERMISSION_READ or BluetoothGattCharacteristic.PERMISSION_WRITE,+ )+ dndCharacteristic.addDescriptor(+ BluetoothGattDescriptor(+ BleConstants.CCCD_UUID,+ BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE,+ ),+ )+ service.addCharacteristic(dataCharacteristic) service.addCharacteristic(controlCharacteristic)+ service.addCharacteristic(dndCharacteristic) server.addService(service) } @@ -157,6 +183,14 @@ class GattServerManager( } private val serverCallback = object : BluetoothGattServerCallback() {+ override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {+ if (newState == android.bluetooth.BluetoothProfile.STATE_DISCONNECTED) {+ dndSubscribers.remove(device.address)+ deviceMtu.remove(device.address)+ pendingAck.remove(device.address)+ }+ }+ override fun onMtuChanged(device: BluetoothDevice, mtu: Int) { deviceMtu[device.address] = mtu }@@ -173,11 +207,18 @@ class GattServerManager( if (responseNeeded) { gattServer?.sendResponse(device, requestId, 0 /* GATT_SUCCESS */, offset, value) }- // Subscription enabled -> stream the current batch.- if (descriptor.uuid == BleConstants.CCCD_UUID && value != null &&+ val enabling = descriptor.uuid == BleConstants.CCCD_UUID && value != null && value.isNotEmpty() && value[0].toInt() != 0- ) {- streamBatch(device)+ if (!enabling) return+ // Both the Data and DND characteristics carry a 0x2902 CCCD, so branch+ // on the owning characteristic.+ when (descriptor.characteristic?.uuid) {+ BleConstants.DATA_CHARACTERISTIC_UUID -> streamBatch(device)+ BleConstants.DND_CHARACTERISTIC_UUID -> {+ dndSubscribers[device.address] = device+ // Push the current value so the client syncs its initial state.+ notify(device, dndCharacteristic, byteArrayOf(currentDnd.toByte()))+ } } } @@ -187,10 +228,15 @@ class GattServerManager( offset: Int, characteristic: BluetoothGattCharacteristic, ) {- // A plain read triggers a fresh stream and returns an empty ack payload.- gattServer?.sendResponse(device, requestId, 0, offset, ByteArray(0))- if (characteristic.uuid == BleConstants.DATA_CHARACTERISTIC_UUID) {- streamBatch(device)+ when (characteristic.uuid) {+ BleConstants.DATA_CHARACTERISTIC_UUID -> {+ // A plain read triggers a fresh stream and returns an empty ack payload.+ gattServer?.sendResponse(device, requestId, 0, offset, ByteArray(0))+ streamBatch(device)+ }+ BleConstants.DND_CHARACTERISTIC_UUID ->+ gattServer?.sendResponse(device, requestId, 0, offset, byteArrayOf(currentDnd.toByte()))+ else -> gattServer?.sendResponse(device, requestId, 0, offset, ByteArray(0)) } } @@ -203,10 +249,14 @@ class GattServerManager( offset: Int, value: ByteArray?, ) {- if (characteristic.uuid == BleConstants.CONTROL_CHARACTERISTIC_UUID &&- value != null && value.isNotEmpty()- ) {- handleControl(device, value)+ if (value != null && value.isNotEmpty()) {+ when (characteristic.uuid) {+ BleConstants.CONTROL_CHARACTERISTIC_UUID -> handleControl(device, value)+ BleConstants.DND_CHARACTERISTIC_UUID -> {+ currentDnd = value[0].toInt()+ onRemoteDnd(currentDnd)+ }+ } } if (responseNeeded) { gattServer?.sendResponse(device, requestId, 0, offset, null)@@ -243,20 +293,34 @@ class GattServerManager( var offset = 0 while (offset < payload.size) { val end = minOf(offset + chunkSize, payload.size)- notify(device, payload.copyOfRange(offset, end))+ notify(device, dataCharacteristic, payload.copyOfRange(offset, end)) offset = end } // Zero-length batches still send EOT so the client can complete.- notify(device, BleConstants.EOT_MARKER)+ notify(device, dataCharacteristic, BleConstants.EOT_MARKER) } } + /**+ * Updates the held interruption filter and notifies every subscribed device.+ * Called by the local DndController when the watch's own DnD state changes.+ */+ fun pushLocalDnd(filter: Int) {+ currentDnd = filter+ val bytes = byteArrayOf(filter.toByte())+ dndSubscribers.values.toList().forEach { notify(it, dndCharacteristic, bytes) }+ }+ @Suppress("DEPRECATION")- private fun notify(device: BluetoothDevice, bytes: ByteArray) {+ private fun notify(+ device: BluetoothDevice,+ characteristic: BluetoothGattCharacteristic,+ bytes: ByteArray,+ ) { val server = gattServer ?: return try {- dataCharacteristic.value = bytes- server.notifyCharacteristicChanged(device, dataCharacteristic, false)+ characteristic.value = bytes+ server.notifyCharacteristicChanged(device, characteristic, false) } catch (e: Exception) { Log.e(TAG, "notify failed", e) }
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/DndController.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/DndController.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/DndController.ktnew file mode 100644index 0000000000..906ad08fa0--- /dev/null+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/DndController.kt@@ -0,0 +1,71 @@+package com.vayunmathur.watch.watch.service++import android.app.NotificationManager+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import com.vayunmathur.watch.watch.ble.GattServerManager++/**+ * Bridges the watch's Do-Not-Disturb (notification interruption filter) with the+ * BLE DND characteristic, so a change on either device propagates to the other.+ *+ * Loop guard: whenever we apply a *remote* filter we record it in+ * [lastAppliedFilter]; the resulting ACTION_INTERRUPTION_FILTER_CHANGED broadcast+ * is then recognized as our own echo and not pushed back out. Applying the filter+ * requires notification-policy access; reading/observing it does not.+ */+class DndController(+ context: Context,+ private val gattServer: GattServerManager,+) {+ private val appContext = context.applicationContext+ private val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager++ @Volatile private var lastAppliedFilter = -1+ private var registered = false++ private val receiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context?, intent: Intent?) {+ if (intent?.action == NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED) {+ onLocalChanged()+ }+ }+ }++ fun register() {+ if (registered) return+ appContext.registerReceiver(+ receiver,+ IntentFilter(NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED),+ )+ registered = true+ // Publish the current filter once so a freshly connected phone can sync.+ gattServer.pushLocalDnd(nm.currentInterruptionFilter)+ }++ fun unregister() {+ if (!registered) return+ runCatching { appContext.unregisterReceiver(receiver) }+ registered = false+ }++ /** Applies a filter received from the phone, unless it is our own echo. */+ fun onRemoteDnd(filter: Int) {+ if (!nm.isNotificationPolicyAccessGranted) return+ if (filter == nm.currentInterruptionFilter) return+ lastAppliedFilter = filter+ runCatching { nm.setInterruptionFilter(filter) }+ }++ private fun onLocalChanged() {+ val filter = nm.currentInterruptionFilter+ // Skip the echo from our own setInterruptionFilter call.+ if (filter == lastAppliedFilter) {+ lastAppliedFilter = -1+ return+ }+ gattServer.pushLocalDnd(filter)+ }+}
watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt
diff --git a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.ktindex ec52ac475e..eada4e25bd 100644--- a/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt+++ b/watch/watch/src/main/java/com/vayunmathur/watch/watch/service/SensorBackgroundService.kt@@ -37,6 +37,7 @@ class SensorBackgroundService : Service(), SensorEventListener { private lateinit var sensorManager: SensorManager private lateinit var gattServer: GattServerManager private lateinit var healthServices: HealthServicesCollector+ private lateinit var dndController: DndController private var lastHeartRateAt = 0L // The step counter reports a cumulative count since boot; we store deltas.@@ -47,8 +48,15 @@ class SensorBackgroundService : Service(), SensorEventListener { override fun onCreate() { super.onCreate() val db = SensorDatabase.get(this)- gattServer = GattServerManager(this, db.sensorDao(), scope)+ gattServer = GattServerManager(+ this,+ db.sensorDao(),+ scope,+ onRemoteDnd = { dndController.onRemoteDnd(it) },+ ) healthServices = HealthServicesCollector(this, db.sensorDao(), scope)+ dndController = DndController(this, gattServer)+ dndController.register() sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager } @@ -182,6 +190,7 @@ class SensorBackgroundService : Service(), SensorEventListener { ) gattServer.stop() healthServices.stop()+ dndController.unregister() scope.cancel() super.onDestroy() }
watch/watch/src/main/res/values/strings.xml
diff --git a/watch/watch/src/main/res/values/strings.xml b/watch/watch/src/main/res/values/strings.xmlindex 8fdb8532f3..3c7176bc14 100644--- a/watch/watch/src/main/res/values/strings.xml+++ b/watch/watch/src/main/res/values/strings.xml@@ -29,4 +29,5 @@ <string name="exercise_calories">Calories: %1$s</string> <string name="exercise_distance">Distance: %1$s m</string> <string name="exercise_dash">--</string>+ <string name="grant_dnd_access">Grant DND Access</string> </resources>