I am building Android launcher using Jetpack Compose, and I need to implement widget hosting, thus I need to pass AppWidgetHostView into Compose. I have successfully done this, but widget is not updating. Here is the code:
@Preview
@Composable
private fun WidgetTest(
appWidgetManager: AppWidgetManager = koinInject(),
appWidgetHost: AppWidgetHost = koinInject(),
packageManager: PackageManager = koinInject()
) {
val widget = appWidgetManager.installedProviders.filterNotNull().onEach {
Log.d("widgets", it.loadLabel(packageManager))
}.find { it.loadLabel(packageManager) == "Assistant At a Glance" }!! // I use this as a test widget
Log.d("widgets", "loading widget ${widget.loadLabel(packageManager)}")
val appWidgetId = appWidgetHost.allocateAppWidgetId()
Log.d("widgets", "binding widget ${widget.loadLabel(packageManager)}")
val canBind = appWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, widget.provider)
if (!canBind) {
val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND).apply {
putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, widget.provider)
}
LocalContext.current.startActivity(intent)
}
Log.d("widgets", "building widget ${widget.loadLabel(packageManager)}")
AndroidView(
factory = { context ->
val widgetView = appWidgetHost.createView(context, appWidgetId, widget).apply {
setAppWidget(appWidgetId, widget)
}
Log.d("widgets", "widget built")
widgetView
}
)
}
I tried searching, found that I forgot to set the listener up. I've done this in MainApplication class:
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@MainApplication)
modules(appModule)
}
val appWidgetHost: AppWidgetHost = getKoin().get<AppWidgetHost>()
appWidgetHost.startListening()
}
}
But widget is still not receiving updates