Demystifying Jetpack Glance for app widgets | by Marcel Pintó | Android Developers | Mar, 2022

0
73
Demystifying Jetpack Glance for app widgets | by Marcel Pintó | Android Developers | Mar, 2022


Important: this blog was written for the Glance-alpha03 version. Future versions might obsolete some of the content below.

App widgets mechanism (source)
class MyAppWidgetReceiver : GlanceAppWidgetReceiver() {  override val glanceAppWidget = MyAppWidget()}

Note: There may be use cases for capturing app widget events such as onEnabled, but it’s not required for building the UI.

Box(modifier = modifier
.appWidgetBackground()
.background(R.color.m3_sys_color_dynamic_dark_background)
) { … }

Note: We are using the color resources provided by the Material Components library. To handle day or night themes or backward compatible devices, wrap the color into another ID and redefine it in each folder (i.e: values/colors.xml, values-v31/colors.xml, …)

<shape android:shape=”rectangle”>  <corners 
android:radius=”@dimen/app_widget_background_corner_radius” />
<solid android:color=”@color/color_background” /></shape>
Box(modifier = modifier.background(
ImageProvider(R.drawable.rounded_corner_background)
))
// Update a specific instance of MyAppWidget.
MyAppWidget().update(context, glanceId)
// Update all placed instances of MyAppWidget.
MyAppWidget().updateAll(context)
// Iterate over all placed instances of MyAppWidget
// and update if the state of the instance matches
// the given predicate.
MyAppWidget().updateIf<Preferences>(context) { state ->
state[KEY_TYPE] == TYPE_DESTINATION
}

Note: Use the GlanceAppWidgetManager.getGlanceIds(..) method to retrieve the GlanceIds.

// Define the state definition in your app widget…
override val stateDefinition = PreferencesGlanceStateDefinition
// … inside a composable.
val counter: Int = currentState(CounterKey) ?: 0
// … somewhere outside of the composition (e.g ActionCallback).
updateAppWidgetState(context, glanceId) { state ->
state[CounterKey] = (state[CounterKey] ?: 0) + 1
}
// Don’t forget to trigger the update. :)
MyAppWidget().update(context, glanceId)

Note: updateAppWidgetState doesn’t automatically trigger the app widget update. You must manually trigger it.

Android Studio Run configuration panel

PS: feel free to ping me on Twitter (@marxallski) and show me what you create with Glance!





Source link

Leave a reply

Please enter your comment!
Please enter your name here