Skip to content

Add Recent Orders Widget #1567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
18 changes: 15 additions & 3 deletions Jetsnack/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,22 @@ plugins {
}

android {
compileSdk = libs.versions.compileSdk.get().toInt()
compileSdk =
libs.versions.compileSdk
.get()
.toInt()
namespace = "com.example.jetsnack"

defaultConfig {
applicationId = "com.example.jetsnack"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
minSdk =
libs.versions.minSdk
.get()
.toInt()
targetSdk =
libs.versions.targetSdk
.get()
.toInt()
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
Expand Down Expand Up @@ -131,4 +140,7 @@ dependencies {
androidTestImplementation(libs.kotlinx.coroutines.test)
androidTestImplementation(libs.androidx.compose.ui.test)
androidTestImplementation(libs.androidx.compose.ui.test.junit4)

implementation(libs.androidx.glance.appwidget)
implementation(libs.androidx.glance.preview)
}
11 changes: 11 additions & 0 deletions Jetsnack/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@
android:theme="@style/Theme.Jetsnack"

>
<receiver
android:name=".widget.RecentOrdersWidgetReceiver"
android:label="@string/snack_order_widget_name"
android:exported="false">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/snack_order_widget_info" />
</receiver>

<profileable
android:shell="true"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2020 The Android Open Source Project
* Copyright 2020-2025 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.
Expand All @@ -16,15 +16,42 @@

package com.example.jetsnack.ui

import android.appwidget.AppWidgetManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.lifecycle.lifecycleScope
import com.example.jetsnack.widget.RecentOrdersWidgetReceiver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
lifecycleScope.launch(Dispatchers.Default) {
setWidgetPreviews()
}
}
setContent { JetsnackApp() }
}

@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
suspend fun setWidgetPreviews() {
val receiver = RecentOrdersWidgetReceiver::class
val installedProviders = getSystemService(AppWidgetManager::class.java).installedProviders
val providerInfo = installedProviders.firstOrNull {
it.provider.className ==
receiver.qualifiedName
}
providerInfo?.generatedPreviewCategories.takeIf { it == 0 }?.let {
// Set previews if this provider if unset
GlanceAppWidgetManager(this).setWidgetPreviews(receiver)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2020 The Android Open Source Project
* Copyright 2020-2025 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.
Expand Down Expand Up @@ -76,6 +76,7 @@ import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.navDeepLink
import com.example.jetsnack.R
import com.example.jetsnack.ui.LocalNavAnimatedVisibilityScope
import com.example.jetsnack.ui.components.JetsnackSurface
Expand Down Expand Up @@ -140,7 +141,12 @@ fun NavGraphBuilder.addHomeGraph(onSnackSelected: (Long, String, NavBackStackEnt
modifier,
)
}
composable(HomeSections.CART.route) { from ->
composable(
HomeSections.CART.route,
deepLinks = listOf(
navDeepLink { uriPattern = "https://jetsnack.example.com/home/cart" },
),
) { from ->
Cart(
onSnackClick = { id, origin -> onSnackSelected(id, origin, from) },
modifier,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2023-2025 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.jetsnack.widget

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.glance.action.ActionParameters

internal val ActionSourceMessageKey = ActionParameters.Key<String>("actionSourceMessageKey")

/**
* Activity that is launched on clicks from different parts of sample widgets. Displays string
* describing source of the click.
*/
class ActionDemonstrationActivity : ComponentActivity() {

override fun onResume() {
super.onResume()
setContent {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
val source = intent.getStringExtra(ActionSourceMessageKey.name) ?: "Unknown"
Text("Launched from $source")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* Copyright 2025 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.jetsnack.widget

import android.content.Context
import android.content.Intent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.glance.GlanceId
import androidx.glance.GlanceTheme
import androidx.glance.LocalContext
import androidx.glance.LocalSize
import androidx.glance.appwidget.AppWidgetId
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.SizeMode
import androidx.glance.appwidget.action.actionStartActivity
import androidx.glance.appwidget.provideContent
import com.example.jetsnack.R
import com.example.jetsnack.ui.MainActivity
import com.example.jetsnack.widget.data.RecentOrdersDataRepository
import com.example.jetsnack.widget.data.RecentOrdersDataRepository.Companion.getImageTextListDataRepo
import com.example.jetsnack.widget.layout.ImageTextListItemData
import com.example.jetsnack.widget.layout.ImageTextListLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class RecentOrdersWidget : GlanceAppWidget() {
// Unlike the "Single" size mode, using "Exact" allows us to have better control over rendering in
// different sizes. And, unlike the "Responsive" mode, it doesn't cause several views for each
// supported size to be held in the widget host's memory.
override val sizeMode: SizeMode = SizeMode.Exact

override val previewSizeMode = SizeMode.Responsive(
setOf(
DpSize(256.dp, 115.dp), // 4x2 cell min size
DpSize(260.dp, 180.dp), // Medium width layout, height with header
),
)

override suspend fun provideGlance(context: Context, id: GlanceId) {
val repo = getImageTextListDataRepo(id)

val initialItems = withContext(Dispatchers.Default) {
repo.load(context)
}

provideContent {
GlanceTheme {
val items by repo.data().collectAsState(initial = initialItems)

key(LocalSize.current) {
WidgetContent(
items = items,
shoppingCartActionIntent = Intent(
context.applicationContext,
MainActivity::class.java,
)
.setAction(Intent.ACTION_VIEW)
.setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK,
)
.setData("https://jetsnack.example.com/home/cart".toUri()),
)
}
}
}
}

@Composable
fun WidgetContent(items: List<ImageTextListItemData>, shoppingCartActionIntent: Intent) {
val context = LocalContext.current

ImageTextListLayout(
items = items,
title = context.getString(R.string.widget_title),
titleIconRes = R.drawable.widget_logo,
titleBarActionIconRes = R.drawable.shopping_cart,
titleBarActionIconContentDescription = context.getString(
R.string.shopping_cart_button_label,
),
titleBarAction = actionStartActivity(shoppingCartActionIntent),
shoppingCartActionIntent = shoppingCartActionIntent,
)
}

override suspend fun providePreview(context: Context, widgetCategory: Int) {
val repo = RecentOrdersDataRepository()
val items = repo.load(context)

provideContent {
GlanceTheme {
WidgetContent(
items = items,
shoppingCartActionIntent = Intent(),
)
}
}
}
}

class RecentOrdersWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget = RecentOrdersWidget()

override fun onDeleted(context: Context, appWidgetIds: IntArray) {
appWidgetIds.forEach {
RecentOrdersDataRepository.cleanUp(AppWidgetId(appWidgetId = it))
}
super.onDeleted(context, appWidgetIds)
}
}
Loading
Loading