weather: added a widget
- Commit
ac0d4becf7c15e74ebbcdf539c4b07ea8deeea91- Author
- Vayun Mathur <[email protected]>
- When
- 2026-05-30 18:29 UTC (6 months ago)
- Parents
25a5aa8
Diff
weather/build.gradle.kts
diff --git a/weather/build.gradle.kts b/weather/build.gradle.ktsindex 0df89e7979..d23f9965c6 100644--- a/weather/build.gradle.kts+++ b/weather/build.gradle.kts@@ -11,6 +11,7 @@ android { dependencies { implementation(project(":library:network"))+ implementation(project(":library:widgets")) implementation(libs.androidx.datastore.preferences) implementRoom(libs) }
weather/src/main/AndroidManifest.xml
diff --git a/weather/src/main/AndroidManifest.xml b/weather/src/main/AndroidManifest.xmlindex 5c3de700d9..92b7b82278 100644--- a/weather/src/main/AndroidManifest.xml+++ b/weather/src/main/AndroidManifest.xml@@ -33,5 +33,17 @@ android:name=".intents.GetWeatherByNameIntent" android:exported="true" android:theme="@android:style/Theme.NoDisplay" />++ <!-- Glance widget receiver -->+ <receiver+ android:name=".glance.WeatherGlanceWidgetReceiver"+ 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/weather_glance_widget_info" />+ </receiver> </application> </manifest>
weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.kt b/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.ktnew file mode 100644index 0000000000..c865e87a53--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.kt@@ -0,0 +1,222 @@+package com.vayunmathur.weather.glance++import android.content.Context+import android.content.Intent+import android.provider.AlarmClock+import androidx.compose.runtime.Composable+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.ImageProvider+import androidx.glance.Image+import androidx.glance.LocalContext+import androidx.glance.action.clickable+import androidx.glance.appwidget.GlanceAppWidget+import androidx.glance.appwidget.action.actionStartActivity+import androidx.glance.appwidget.cornerRadius+import androidx.glance.appwidget.provideContent+import androidx.glance.background+import androidx.glance.layout.Alignment+import androidx.glance.layout.Box+import androidx.glance.layout.Column+import androidx.glance.layout.Row+import androidx.glance.layout.fillMaxHeight+import androidx.glance.layout.fillMaxSize+import androidx.glance.layout.fillMaxWidth+import androidx.glance.layout.padding+import androidx.glance.layout.size+import androidx.glance.layout.width+import androidx.glance.text.FontWeight+import androidx.glance.text.Text+import androidx.glance.text.TextStyle+import com.vayunmathur.library.util.buildDatabase+import com.vayunmathur.library.widgets.DynamicThemeGlance+import com.vayunmathur.weather.MainActivity+import com.vayunmathur.weather.data.WeatherDatabase+import com.vayunmathur.weather.network.ForecastResponse+import com.vayunmathur.weather.util.weatherConditionForCode+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.format+import kotlinx.datetime.format.MonthNames+import kotlinx.datetime.format.Padding+import kotlinx.datetime.format.char+import kotlinx.datetime.toLocalDateTime+import kotlinx.serialization.json.Json+import kotlin.math.roundToInt+import kotlin.time.Clock++/**+ * Snapshot of cached weather used by the 4x1 widget. Populated from the+ * most-recent [com.vayunmathur.weather.data.WeatherCache] row for the+ * user's primary saved location (preferring the device-location row).+ * `null` while no forecast has been cached yet — the widget renders a+ * dash in that case rather than failing to load.+ */+data class WidgetWeather(+ val temperatureCelsius: Double,+ val weatherCode: Int,+ val isDay: Boolean,+)++class WeatherGlanceWidget : GlanceAppWidget() {+ override suspend fun provideGlance(context: Context, id: GlanceId) {+ val weather = loadWeatherSnapshot(context)++ provideContent {+ DynamicThemeGlance(context) {+ Content(weather)+ }+ }+ }++ private suspend fun loadWeatherSnapshot(context: Context): WidgetWeather? {+ return try {+ val db = context.buildDatabase<WeatherDatabase>(dbName = "weather-db")+ val dao = db.weatherDao()+ // Prefer the device-current row, fall back to the first pinned location.+ val location = dao.getCurrentDeviceLocation()+ ?: dao.getLocations().firstOrNull()+ ?: return null+ val cache = dao.getCache(+ roundCoord(location.latitude),+ roundCoord(location.longitude),+ ) ?: return null+ val json = Json { ignoreUnknownKeys = true }+ val forecast = runCatching {+ json.decodeFromString<ForecastResponse>(cache.forecastJson)+ }.getOrNull() ?: return null+ val current = forecast.current ?: return null+ WidgetWeather(+ temperatureCelsius = current.temperature,+ weatherCode = current.weatherCode,+ isDay = current.isDay != 0,+ )+ } catch (e: Exception) {+ null+ }+ }++ private fun roundCoord(value: Double): Double =+ (value * 10000.0).let { kotlin.math.round(it) } / 10000.0+}++/**+ * Generic intent that asks the user's default clock app to open. Falls+ * back gracefully — every Android device ships a handler for+ * [AlarmClock.ACTION_SHOW_ALARMS].+ */+private fun clockIntent(): Intent = Intent(AlarmClock.ACTION_SHOW_ALARMS).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+}++/**+ * Generic intent that opens the user's default calendar app via the+ * standard [Intent.CATEGORY_APP_CALENDAR] launcher category.+ */+private fun calendarIntent(): Intent = Intent(Intent.ACTION_MAIN).apply {+ addCategory(Intent.CATEGORY_APP_CALENDAR)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+}++@Composable+private fun Content(weather: WidgetWeather?) {+ val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())+ Row(+ modifier = GlanceModifier+ .fillMaxSize()+ .background(GlanceTheme.colors.surface)+ .cornerRadius(20.dp)+ .padding(horizontal = 12.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // Left column: time stacked over date, each independently clickable.+ Column(+ modifier = GlanceModifier.defaultWeight().fillMaxHeight(),+ verticalAlignment = Alignment.CenterVertically,+ horizontalAlignment = Alignment.Start,+ ) {+ Box(+ modifier = GlanceModifier+ .clickable(actionStartActivity(clockIntent())),+ ) { TimeBlock(now) }+ Box(+ modifier = GlanceModifier+ .padding(top = 2.dp)+ .clickable(actionStartActivity(calendarIntent())),+ ) { DateBlock(now) }+ }+ // Right: large weather icon + temperature, clickable into this app.+ Box(+ modifier = GlanceModifier.defaultWeight().fillMaxHeight()+ .padding(start = 8.dp)+ .clickable(actionStartActivity(Intent(LocalContext.current, MainActivity::class.java).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ })),+ contentAlignment = Alignment.CenterEnd,+ ) { WeatherBlock(weather) }+ }+}++@Composable+private fun TimeBlock(now: LocalDateTime) {+ val timeFormat = LocalDateTime.Format {+ hour(Padding.NONE); char(':'); minute(Padding.ZERO)+ }+ Text(+ text = now.format(timeFormat),+ style = TextStyle(+ color = GlanceTheme.colors.onSurface,+ fontSize = 40.sp,+ fontWeight = FontWeight.Bold,+ ),+ )+}++@Composable+private fun DateBlock(now: LocalDateTime) {+ val dateFormat = LocalDateTime.Format {+ monthName(MonthNames.ENGLISH_ABBREVIATED); char(' '); day(Padding.NONE)+ }+ Text(+ text = now.format(dateFormat),+ style = TextStyle(+ color = GlanceTheme.colors.onSurface,+ fontSize = 18.sp,+ fontWeight = FontWeight.Medium,+ ),+ )+}++@Composable+private fun WeatherBlock(weather: WidgetWeather?) {+ if (weather == null) {+ Text(+ text = "—",+ style = TextStyle(+ color = GlanceTheme.colors.onSurface,+ fontSize = 36.sp,+ fontWeight = FontWeight.Bold,+ ),+ )+ return+ }+ val condition = weatherConditionForCode(weather.weatherCode)+ Row(verticalAlignment = Alignment.CenterVertically) {+ Image(+ provider = ImageProvider(condition.iconRes(weather.isDay)),+ contentDescription = condition.label,+ modifier = GlanceModifier.size(44.dp),+ )+ Text(+ text = " ${weather.temperatureCelsius.roundToInt()}°",+ style = TextStyle(+ color = GlanceTheme.colors.onSurface,+ fontSize = 36.sp,+ fontWeight = FontWeight.Bold,+ ),+ )+ }+}
weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidgetReceiver.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidgetReceiver.kt b/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidgetReceiver.ktnew file mode 100644index 0000000000..d5eddb9f2a--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidgetReceiver.kt@@ -0,0 +1,14 @@+package com.vayunmathur.weather.glance++import android.content.Context+import androidx.glance.appwidget.GlanceAppWidgetReceiver+import com.vayunmathur.library.widgets.scheduleHourlyUpdate++class WeatherGlanceWidgetReceiver : GlanceAppWidgetReceiver() {+ override val glanceAppWidget: WeatherGlanceWidget = WeatherGlanceWidget()++ override fun onEnabled(context: Context) {+ super.onEnabled(context)+ context.scheduleHourlyUpdate(WeatherGlanceWidget::class)+ }+}
weather/src/main/res/xml/weather_glance_widget_info.xml
diff --git a/weather/src/main/res/xml/weather_glance_widget_info.xml b/weather/src/main/res/xml/weather_glance_widget_info.xmlnew file mode 100644index 0000000000..1e9579c2cd--- /dev/null+++ b/weather/src/main/res/xml/weather_glance_widget_info.xml@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="utf-8"?>+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"+ android:minWidth="250dp"+ android:minHeight="80dp"+ android:targetCellWidth="4"+ android:targetCellHeight="1"+ android:updatePeriodMillis="0"+ android:initialLayout="@layout/glance_widget_initial_layout"+ android:resizeMode="horizontal"+ android:widgetCategory="home_screen" />