I'm currently working with a widget Android app using Kotlin 1.9.10 and Glance 1.0.0. I want to pin widget to home screen programmatically. I can get the widget id in onReceive fun but I want to pass more value into that.
I'm using this piece of code to pin my widget to home screen.
val appWidgetManager = AppWidgetManager.getInstance(context)
val myProvider = ComponentName(context, MyWidgetReceiver::class.java)
val pinnedWidgetCallbackIntent = Intent(Intent.ACTION_MAIN)
pinnedWidgetCallbackIntent.addCategory(Intent.CATEGORY_HOME)
pinnedWidgetCallbackIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val successCallback = PendingIntent.getActivity(
context, 0,
pinnedWidgetCallbackIntent, PendingIntent.FLAG_IMMUTABLE
)
appWidgetManager.requestPinAppWidget(myProvider, null, successCallback)
And in my Receiver, I override onReceive fun to get the Widget ID which have just been pinned to home screen.
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
if (intent.action == AppWidgetManager.ACTION_APPWIDGET_UPDATE) {
val extras = intent.extras
val widgetId = extras?.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS)?.firstOrNull() ?: -1
}
}
But the problem is I want to pass one more value so that I can save it to the local storage as map, using widget id as key. How can I do that, please help me.
Reading the
requestPinAppWidgetdocumentation I've found that you can pass aBundleas a parameter and you are passingnull.So you should change this
To this
In case you want to do it after it, you should use
updateAppWidgetOptionsand send also aBundleand override theonUpdatemethod and getting the values using