Search code examples
android-widgetandroid-jetpack-composeglanceglance-appwidget

How to update the AppWidgetState of a Compose Glance Widget from a Configuration/Main Activity?


My latest idea was to use

updateAppWidgetState(context = context, definition = PreferencesGlanceStateDefinition, glanceId = glanceId) {
   // ...
}

and

GlanceWidget().update(context = context, glanceId = glanceId)

but I don't have access to glanceId.

The background of the question is that I want to add the uid to the AppWidgetState as described in this question: How to get the AppWidgetId of a Compose Glance widget?

How can I get the glanceId (e.g. from the appWidgetId that I have access to in the Configure activity) or how else would I achieve this?


Solution

  • I finally solved my own problem a few months later. With version 1.0.0-alpha04 released a month ago, there is a new getGlanceIdBy method.

    New method to get GlanceId from an existing appWidgetId or an intent from a configuration activity (Icb70c, b/230391946)

    My code now looks like this:

    // Try block because getGlanceIdBy throws IllegalArgumentException if no GlanceId is found for this appWidgetId.
    try {
        val glanceAppWidgetManager = GlanceAppWidgetManager(context)
        val glanceId: GlanceId = glanceAppWidgetManager.getGlanceIdBy(appWidgetId)
        updateAppWidgetState(context = context, glanceId = glanceId) {
            it[intPreferencesKey("uid")] = uid
        }
        val glanceAppWidget: GlanceAppWidget = GlanceWidget()
    
        glanceAppWidget.update(context, glanceId)
    } catch (e: IllegalArgumentException) {
        Log.d(TAG, "No GlanceId found for this appWidgetId.")
    }