Skip to content
Open
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ These are the recipes and what they demonstrate.
- **[Debounce](app/src/main/java/com/example/appstaterecipes/debounce)**: Demonstrates how to debounce rapidly changing state (such as search queries) using `DebounceEffect` and `rememberDebounced`.
- **[Sample](app/src/main/java/com/example/appstaterecipes/sample)**: Demonstrates how to periodically sample high-frequency state streams (such as accelerometer sensor data) using `SampleEffect` and `rememberSampled`.

#### UI surfaces & nested transforms
- **[Glance Widget](app/src/main/java/com/example/appstaterecipes/glance)**: Demonstrates how to define a `transform` for a Jetpack Glance home-screen widget (`GlanceAppWidget`) and layer nested `transform` blocks across an app screen and widget with dynamic read tracking.

### Full-app recipes
Full-app recipes live under `apps/*` (such as `apps/browser/`). Each is an independent Android application module that can be launched directly via its own Android Studio Run Configuration (e.g. `apps.browser`) or deployed to a device and opened from the main Recipe Picker (`:app`). Shared architecture components (like `StateStoreOwner`, `StateStoreViewerActivity`, and common theming) are provided by the shared `:core` library module.

Expand Down
4 changes: 4 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,12 @@ dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.appstate.transform)
implementation(libs.androidx.glance.appwidget)
implementation(libs.androidx.glance.material3)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.viewmodel.compose)
testImplementation(libs.androidx.appstate.transform.testing)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.junit)
debugImplementation(libs.androidx.compose.ui.tooling)
}
15 changes: 15 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,21 @@
<activity
android:name=".sample.SampleActivity"
android:exported="false" />
<activity
android:name=".glance.GlanceActivity"
android:exported="false" />

<receiver
android:name=".glance.FocusWidgetReceiver"
android:exported="true"
android:label="FocusFlow">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/focus_widget_info" />
</receiver>
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import com.example.appstaterecipes.debounce.DebounceActivity
import com.example.appstaterecipes.glance.GlanceActivity
import com.example.appstaterecipes.sample.SampleActivity
import com.example.appstaterecipes.ui.excludeBottom
import com.example.appstaterecipes.ui.onlyBottom
Expand Down Expand Up @@ -105,6 +106,12 @@ private val recipes = listOf(
description = "Throttles high-frequency streams into a fixed periodic cadence (e.g. sensor readings).",
target = RecipeTarget.InternalActivity(SampleActivity::class.java),
),
Heading("Transform — UI Surfaces & Nested Transforms"),
Recipe(
name = "Glance Widget",
description = "Derives state for a Jetpack Glance home-screen widget and layers nested transforms across surfaces.",
target = RecipeTarget.InternalActivity(GlanceActivity::class.java),
),
Heading("StateStore — Multi-Window Navigation"),
Recipe(
name = "Browser Multi-Window Navigation",
Expand Down
114 changes: 114 additions & 0 deletions app/src/main/java/com/example/appstaterecipes/glance/FocusGraph.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* 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
*
* http://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.appstaterecipes.glance

import android.content.Context
import androidx.appstate.transform.listener
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.glance.appwidget.updateAll
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

internal val sampleFocusTasks = listOf(
FocusTask(
id = "write-ads-talk",
title = "Write the ADS talk",
durationMinutes = 25,
),
FocusTask(
id = "reply-design-doc",
title = "Reply to design doc comments",
durationMinutes = 15,
),
FocusTask(
id = "plan-q1-roadmap",
title = "Plan Q1 roadmap",
durationMinutes = 25,
),
)

class InMemoryTaskRepository(
initialTasks: List<FocusTask> = sampleFocusTasks,
initialCompletedToday: Int = 0,
) : TaskRepository {
private val _tasksFlow = MutableStateFlow(initialTasks)
override val tasksFlow: StateFlow<List<FocusTask>> = _tasksFlow.asStateFlow()

private val _completedTodayFlow = MutableStateFlow(initialCompletedToday)
override val completedTodayFlow: StateFlow<Int> = _completedTodayFlow.asStateFlow()

override fun recordCompletedSession() {
_completedTodayFlow.update { it + 1 }
}
}

/**
* Process-scoped holder shared between [GlanceActivity] and [FocusWidget].
*
* Uses [listener] from `androidx.appstate.transform` to wake any placed [FocusWidget] instances
* via [FocusWidget.updateAll] when state changes outside an active Glance worker session.
* Note that `updateAll` does not restart `provideGlance` if a Glance session is already running.
*/
internal class FocusContainer(appContext: Context) {
private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

val taskRepository = InMemoryTaskRepository()
val focusManager = FocusSessionManager(
taskRepository = taskRepository,
scope = appScope,
)

val defaultTask: FocusTask
get() = taskRepository.tasksFlow.value.first()

init {
appScope.launch {
listener {
val summary by focusManager.summary
val completedToday by taskRepository.completedTodayFlow.collectAsState()

LaunchedEffect(summary, completedToday) {
val glanceIds = GlanceAppWidgetManager(appContext)
.getGlanceIds(FocusWidget::class.java)
if (glanceIds.isNotEmpty()) {
FocusWidget().updateAll(appContext)
}
}
}
}
}

companion object {
@Volatile
private var instance: FocusContainer? = null

fun get(context: Context): FocusContainer {
return instance ?: synchronized(this) {
instance ?: FocusContainer(context.applicationContext).also { instance = it }
}
}
}
}
214 changes: 214 additions & 0 deletions app/src/main/java/com/example/appstaterecipes/glance/FocusWidget.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/*
* 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
*
* http://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.appstaterecipes.glance

import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.glance.GlanceId
import androidx.glance.GlanceModifier
import androidx.glance.GlanceTheme
import androidx.glance.action.ActionParameters
import androidx.glance.action.actionStartActivity
import androidx.glance.action.clickable
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.LinearProgressIndicator
import androidx.glance.appwidget.action.ActionCallback
import androidx.glance.appwidget.action.actionRunCallback
import androidx.glance.appwidget.components.FilledButton
import androidx.glance.appwidget.components.OutlineButton
import androidx.glance.appwidget.components.Scaffold
import androidx.glance.appwidget.provideContent
import androidx.glance.layout.Alignment
import androidx.glance.layout.Column
import androidx.glance.layout.Row
import androidx.glance.layout.Spacer
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.fillMaxWidth
import androidx.glance.layout.height
import androidx.glance.layout.padding
import androidx.glance.layout.width
import androidx.glance.text.FontWeight
import androidx.glance.text.Text
import androidx.glance.text.TextStyle
import kotlinx.coroutines.coroutineScope

// [START glance_provide_glance]
class FocusWidget : GlanceAppWidget() {

override suspend fun provideGlance(context: Context, id: GlanceId) {
val container = FocusContainer.get(context)
coroutineScope {
val widgetState = focusWidgetTransform(
summaryState = container.focusManager.summary,
completedTodayFlow = container.taskRepository.completedTodayFlow,
scope = this,
)
provideContent {
val uiState by widgetState
GlanceTheme {
FocusWidgetContent(uiState = uiState)
}
}
}
}
// [END glance_provide_glance]

override suspend fun providePreview(context: Context, widgetCategory: Int) {
val previewState = FocusWidgetUiState(
statusLabel = "Focusing",
taskTitle = "Write the ADS talk",
formattedTime = "24:55",
progress = 0.2f,
primaryAction = WidgetPrimaryAction.Pause,
isSessionActive = true,
completedToday = 1,
)
provideContent {
GlanceTheme {
FocusWidgetContent(uiState = previewState)
}
}
}
}

class FocusWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = FocusWidget()
}

class FocusWidgetPrimaryActionCallback : ActionCallback {
override suspend fun onAction(
context: Context,
glanceId: GlanceId,
parameters: ActionParameters,
) {
val container = FocusContainer.get(context)
container.focusManager.togglePrimaryAction(container.defaultTask)
}
}

class FocusWidgetStopActionCallback : ActionCallback {
override suspend fun onAction(
context: Context,
glanceId: GlanceId,
parameters: ActionParameters,
) {
FocusContainer.get(context).focusManager.stopSession()
}
}

@Composable
private fun FocusWidgetContent(uiState: FocusWidgetUiState) {
Scaffold(
backgroundColor = GlanceTheme.colors.widgetBackground,
modifier = GlanceModifier
.fillMaxSize()
.clickable(actionStartActivity<GlanceActivity>()),
) {
Column(
modifier = GlanceModifier
.fillMaxSize()
.padding(vertical = 12.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = GlanceModifier.fillMaxWidth(),
) {
Text(
text = "FocusFlow",
style = TextStyle(
color = GlanceTheme.colors.onSurfaceVariant,
fontSize = 12.sp,
fontWeight = FontWeight.Medium,
),
)
Spacer(modifier = GlanceModifier.defaultWeight())
Text(
text = "${uiState.completedToday} done today",
style = TextStyle(
color = GlanceTheme.colors.onSurfaceVariant,
fontSize = 12.sp,
),
)
}

Spacer(modifier = GlanceModifier.height(6.dp))

val subtitle = uiState.taskTitle?.let { "${uiState.statusLabel} • $it" }
?: uiState.statusLabel
Text(
text = subtitle,
maxLines = 1,
style = TextStyle(
color = GlanceTheme.colors.primary,
fontSize = 13.sp,
fontWeight = FontWeight.Medium,
),
)

Spacer(modifier = GlanceModifier.defaultWeight())

Row(
verticalAlignment = Alignment.CenterVertically,
modifier = GlanceModifier.fillMaxWidth(),
) {
Text(
text = uiState.formattedTime,
style = TextStyle(
color = GlanceTheme.colors.onSurface,
fontSize = 28.sp,
fontWeight = FontWeight.Bold,
),
)
Spacer(modifier = GlanceModifier.defaultWeight())

if (uiState.isSessionActive) {
OutlineButton(
text = "Stop",
contentColor = GlanceTheme.colors.onSurfaceVariant,
onClick = actionRunCallback<FocusWidgetStopActionCallback>(),
)
Spacer(modifier = GlanceModifier.width(6.dp))
}

val actionLabel = when (uiState.primaryAction) {
WidgetPrimaryAction.Start -> "Start"
WidgetPrimaryAction.Pause -> "Pause"
WidgetPrimaryAction.Resume -> "Resume"
}
FilledButton(
text = actionLabel,
onClick = actionRunCallback<FocusWidgetPrimaryActionCallback>(),
)
}

Spacer(modifier = GlanceModifier.height(8.dp))

LinearProgressIndicator(
progress = uiState.progress,
color = GlanceTheme.colors.primary,
backgroundColor = GlanceTheme.colors.surfaceVariant,
modifier = GlanceModifier
.fillMaxWidth()
.height(6.dp),
)
}
}
}
Loading
Loading