Reputation: 568
I have a Glance widget, and when configuring it initially I save some IDs to Shared Preferences.
These IDs should be read in the provideGlance
method, but it is not called after configuring the widget, even though I call ValueWidget().update(context, glanceId)
.
From the logging I can see that provideGlance
is called before configuring the widget, but not after.
My code:
class ValueWidget : GlanceAppWidget() {
override suspend fun provideGlance(context: Context, id: GlanceId) {
Timber.d("ValueWidget provideGlance: $id")
val appWidgetId = GlanceAppWidgetManager(context).getAppWidgetId(glanceId = id)
val elementIds = ValueWidgetUtils.loadElementIds(widgetId = appWidgetId, context)
provideContent {
Timber.d("ValueWidget provideContent: $id")
}
}
}
The configure activity:
@AndroidEntryPoint
class ValueWidgetConfigureActivity : AppCompatActivity() {
private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
public override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if the user presses the back button.
setResult(RESULT_CANCELED)
setContent {
val coroutineScope = rememberCoroutineScope()
AppTheme(
darkTheme = ThemeUtils.isDarkMode(this)
) {
SelectItemsView(
save = { elementIds ->
// Save to shared preferences
ValueWidgetUtils.insertElementIds(appWidgetId, elementIds.toSet(), this)
coroutineScope.launch {
val context = this@ValueWidgetConfigureActivity
val manager = GlanceAppWidgetManager(context)
val glanceId = manager.getGlanceIdBy(appWidgetId)
// It is the responsibility of the configuration activity to update the app widget
ValueWidget().update(context, glanceId)
// Make sure we pass back the original appWidgetId
val resultValue = Intent()
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
setResult(RESULT_OK, resultValue)
finish()
}
}
)
}
}
// Find the widget id from the intent.
appWidgetId = intent?.extras?.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID
) ?: AppWidgetManager.INVALID_APPWIDGET_ID
// If this activity was started with an intent without an app widget ID, finish with an error.
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish()
return
}
}
}
I can hack around this issue when adding the widget the first time, by adding the below code to provideGlance
.
It does not work after configuring the widget (editing it) though.
var elementIds = ValueWidgetUtils.loadElementIds(appWidgetId, context)
while (elementIds.isEmpty()) {
Timber.d("ValueWidget: No elements selected, waiting for selection")
delay(1000)
elementIds = ValueWidgetUtils.loadElementIds(appWidgetId, context)
}
Upvotes: 1
Views: 23