Skip to content
Draft
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
2 changes: 2 additions & 0 deletions DataLayer/Application/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,6 @@ dependencies {
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.playservices.wearable)
implementation(libs.androidx.fragment.ktx)

testImplementation(libs.junit)
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
Expand All @@ -46,7 +47,6 @@ import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.PutDataMapRequest
import com.google.android.gms.wearable.Wearable
import java.io.ByteArrayOutputStream
import java.time.Duration
import java.time.Instant
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -98,19 +98,18 @@ class MainActivity : ComponentActivity() {
lifecycleScope.launch {
if (isAvailable(capabilityClient)) {
lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
// Set the initial trigger such that the first count will happen in one second.
var lastTriggerTime = Instant.now() - (countInterval - Duration.ofSeconds(1))
// This periodic loop exists only to generate demonstration DataClient
// traffic while the sample activity is visible. Production Wear OS apps
// should prefer event-driven state updates and self-ticking system
// surfaces (such as OngoingActivity StopwatchPart/TimerPart or
// TimeDifferenceComplicationText) over periodic Data Layer ticks.
var nextTriggerRealtimeMs =
SystemClock.elapsedRealtime() + INITIAL_COUNT_DELAY_MS
while (isActive) {
// Figure out how much time we still have to wait until our next desired trigger
// point. This could be less than the count interval if sending the count took
// some time.
delay(
Duration
.between(Instant.now(), lastTriggerTime + countInterval)
.toMillis()
)
// Update when we are triggering sending the count
lastTriggerTime = Instant.now()
val delayMs = nextTriggerRealtimeMs - SystemClock.elapsedRealtime()
if (delayMs > 0L) {
delay(delayMs)
}
sendCount(count)

// Increment the count to send next time
Expand All @@ -119,6 +118,12 @@ class MainActivity : ComponentActivity() {
// is stored in a DataStore and modeled as a proto, see thre Horologist DataLayer sample in
// https://google.github.io/horologist/datalayer/
count++

nextTriggerRealtimeMs =
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = nextTriggerRealtimeMs,
nowRealtimeMs = SystemClock.elapsedRealtime()
)
}
}
}
Expand Down Expand Up @@ -357,7 +362,23 @@ class MainActivity : ComponentActivity() {
private const val CAMERA_CAPABILITY = "camera"
private const val WEAR_CAPABILITY = "wear"
private const val WEAR_SCHEME = "wear"

private val countInterval = Duration.ofSeconds(5)
}
}

internal const val INITIAL_COUNT_DELAY_MS = 1_000L
internal const val COUNT_INTERVAL_MS = 5_000L

/**
* Advances [previousTriggerRealtimeMs] on a fixed [intervalMs] monotonic schedule so wakeup
* overshoots do not accumulate across iterations and stalls longer than [intervalMs] skip
* already-elapsed intervals without emitting a catch-up burst.
*/
internal fun nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs: Long,
nowRealtimeMs: Long,
intervalMs: Long = COUNT_INTERVAL_MS
): Long {
require(intervalMs > 0L) { "intervalMs must be positive" }
val missedIntervals = maxOf(0L, nowRealtimeMs - previousTriggerRealtimeMs) / intervalMs
return previousTriggerRealtimeMs + (missedIntervals + 1L) * intervalMs
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright 2026 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.datalayer

import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test

class MainActivityCountScheduleTest {
@Test
fun repeatedWakeupOvershoots_stayLockedToMonotonicGrid() {
val startRealtimeMs = 10_000L
var nextTriggerRealtimeMs = startRealtimeMs + INITIAL_COUNT_DELAY_MS
assertEquals(11_000L, nextTriggerRealtimeMs)

for (step in 0 until 100) {
val overshootMs = 4L + (step % 16) // +4 ms..+19 ms wakeup overshoot per tick
val wakeupRealtimeMs = nextTriggerRealtimeMs + overshootMs
nextTriggerRealtimeMs =
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = nextTriggerRealtimeMs,
nowRealtimeMs = wakeupRealtimeMs
)

val expectedTriggerRealtimeMs =
startRealtimeMs + INITIAL_COUNT_DELAY_MS + (step + 1L) * COUNT_INTERVAL_MS
assertEquals(expectedTriggerRealtimeMs, nextTriggerRealtimeMs)
}
}

@Test
fun subIntervalSendLatency_preservesFiveSecondCadence() {
val firstTriggerRealtimeMs = 1_000L

// Typical 45 ms sendCount IPC after an 8 ms wakeup overshoot (completes at 1,053 ms):
val typicalSendCompletionMs = 1_008L + 45L
val nextAfterTypicalSend =
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = firstTriggerRealtimeMs,
nowRealtimeMs = typicalSendCompletionMs
)
assertEquals(6_000L, nextAfterTypicalSend)
assertEquals(4_947L, nextAfterTypicalSend - typicalSendCompletionMs)

// Near-interval 4,999 ms sendCount IPC after exact wakeup (completes at 5,999 ms):
val slowSubIntervalCompletionMs = firstTriggerRealtimeMs + 4_999L
val nextAfterSlowSubIntervalSend =
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = firstTriggerRealtimeMs,
nowRealtimeMs = slowSubIntervalCompletionMs
)
assertEquals(6_000L, nextAfterSlowSubIntervalSend)
assertEquals(1L, nextAfterSlowSubIntervalSend - slowSubIntervalCompletionMs)
}

@Test
fun multiIntervalStallAndExactBoundaries_skipMissedIntervalsWithoutBurst() {
val previousTriggerRealtimeMs = 1_000L

// 12.3 s stall skips the 6,000 ms and 11,000 ms slots and schedules 16,000 ms.
val stalledNowMs = previousTriggerRealtimeMs + 12_300L
val afterStall =
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = previousTriggerRealtimeMs,
nowRealtimeMs = stalledNowMs
)
assertEquals(16_000L, afterStall)
assertTrue(afterStall > stalledNowMs)

// Exact 5,000 ms boundary (now = 6,000 ms) advances strictly into the future (11,000 ms).
val exactSingleBoundaryNowMs = previousTriggerRealtimeMs + COUNT_INTERVAL_MS
val afterExactSingleBoundary =
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = previousTriggerRealtimeMs,
nowRealtimeMs = exactSingleBoundaryNowMs
)
assertEquals(11_000L, afterExactSingleBoundary)
assertTrue(afterExactSingleBoundary > exactSingleBoundaryNowMs)

// Early timer wakeup (now < previousTrigger) still advances by exactly one interval.
val afterEarlyWakeup =
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = previousTriggerRealtimeMs,
nowRealtimeMs = 998L
)
assertEquals(6_000L, afterEarlyWakeup)
}

@Test
fun nonPositiveInterval_throwsIllegalArgumentException() {
assertThrows(IllegalArgumentException::class.java) {
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = 1_000L,
nowRealtimeMs = 1_000L,
intervalMs = 0L
)
}
assertThrows(IllegalArgumentException::class.java) {
nextCountTriggerRealtimeMs(
previousTriggerRealtimeMs = 1_000L,
nowRealtimeMs = 1_000L,
intervalMs = -5_000L
)
}
}
}
Loading