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

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
) { … }

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(
// Update a specific instance of MyAppWidget.
MyAppWidget().update(context, glanceId)
// Update all placed instances of MyAppWidget.
// Iterate over all placed instances of MyAppWidget
// and update if the state of the instance matches
// the given predicate.
MyAppWidget().updateIf<Preferences>(context) { state ->

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