Glance Widget
Dependencies
Section titled “Dependencies”implementation("androidx.glance:glance-appwidget:1.1.0")implementation("androidx.glance:glance-material3:1.1.0")Create a Receiver
Section titled “Create a Receiver”class MyReceiver : GlanceAppWidgetReceiver() { override val glanceAppWidget: GlanceAppWidget = MyGlanceWidget()}Create widget UI
Section titled “Create widget UI”class MyGlanceWidget : GlanceAppWidget() { @SuppressLint("RestrictedApi") override suspend fun provideGlance(context: Context, id: GlanceId) { provideContent { /* composable function here... */ } }}Add appwidget provider for meta data
Section titled “Add appwidget provider for meta data”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" />In AndroidManifest.xml
Section titled “In AndroidManifest.xml”⚠️ 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>Auto Update Widget When Rebuild
Section titled “Auto Update Widget When Rebuild”
BarWidgetis aGlanceAppWidget()in this example
Method 1: Via Application Class
Section titled “Method 1: Via Application Class”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.xmland add the widget update method toonCreate()to update the widget when app launches
Method 2: Via MainActivity
Section titled “Method 2: Via MainActivity”Under MainActivity:
suspend fun refreshWidget(context: Context) { BarWidget().updateAll(context)}In Composable:
CoroutineScope(Dispatchers.Main).launch { refreshWidget(this@MainActivity)}