Using SwiftUI and Compose to develop App Widgets on iOS and Android
Posted on November 6, 2021
There was announcement at Android Dev Summit 2021 recently about a new
Compose based Glance API for the development of Android App Widgets. Given ability since iOS14 to develop iOS App Widgets using
SwiftUI I thought it would be interesting to compare approaches used and to do so in a project where
both widgets consume the same Kotlin Mutliplatform shared code (in this case in the BikeShare KMM sample).
Update Nov 14th 2021: I’ve updated article to reflect recent changes to Glance API.
Compose based Android App Widget
For the Android app widget we’re going to use, as mentioned, the new Compose based Glance APIs. An important thing to note at this
point is that Glance is still very much in development (only available right now through snapshot dependencies) and, as such, APIs
will almost certainly change.
I’ll cover below the various moving parts/plumbing needed to setup a Glance based widget but interesting to start by
looking at the Compose based code for the widget itself. We’ll show details for the iOS widget later and hopefully should be
apparent again how similar these approaches and associated code are.
To make this widget available we also need to create a GlanceAppWidgetReceiver.
And then we can use code elsewhere in project to update widget once new data is available (polling in
this case for updated bike share information for particular station)
Regarding remaining plumbing required to use this, we needed to add following to AndroidManifest.xml
As with the Android app widget we’ll start by showing the code for the widget itself.
We also need to provide a TimelineProvider to provide the data needed for the widget. Note that we’re using same fetchBikeShareInfo
function from shared Kotlin Multiplatform code that our Android widget is using.
As we’re consuming shared Kotlin Multiplatform code in this project using CocoaPods we also needed to add following to Podfile
for the iOS project and run pod install.
And finally this is what those widgets looks like right now on iOS and Android