Skip to content

Glance Widget

implementation("androidx.glance:glance-appwidget:1.1.0")
implementation("androidx.glance:glance-material3:1.1.0")
class MyReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = MyGlanceWidget()
}
class MyGlanceWidget : GlanceAppWidget() {
@SuppressLint("RestrictedApi")
override suspend fun provideGlance(context: Context, id: GlanceId) {
provideContent {
/* composable function here... */
}
}
}

Create a xml file under res/xml/:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/app_name"
android:minWidth="200dp"
android:minHeight="100dp"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="1000" />

⚠️ HINT: android.appwidget.* - the widget is appwidget

<receiver
android:name=".MyReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/music_widget_info" />
</receiver>

BarWidget is a GlanceAppWidget() in this example

In Application Class, declare a scope to run suspend action:

private val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)

Run the update widget method:

appScope.launch {
BarWidget().updateAll(applicationContext)
}

⚠️ Remember to bind the application class in AndroidManifest.xml and add the widget update method to onCreate() to update the widget when app launches

Under MainActivity:

suspend fun refreshWidget(context: Context) {
BarWidget().updateAll(context)
}

In Composable:

CoroutineScope(Dispatchers.Main).launch {
refreshWidget(this@MainActivity)
}