Skip to content

Instantly share code, notes, and snippets.

@adityabhaskar
Created December 7, 2020 11:29
Show Gist options
  • Select an option

  • Save adityabhaskar/9c1ba052d0ee2b3d9c9650f5f0c98490 to your computer and use it in GitHub Desktop.

Select an option

Save adityabhaskar/9c1ba052d0ee2b3d9c9650f5f0c98490 to your computer and use it in GitHub Desktop.
Pinning an Android widget programmatically
private fun pinWidget(context: Context) {
val appWidgetManager = context.getSystemService(AppWidgetManager::class.java) ?: return
val myProvider = ComponentName(context.applicationContext, TaskListWidget::class.java)
if (!appWidgetManager.isRequestPinAppWidgetSupported) {
Timber.d("Widgets not supported")
return
}
// Create the PendingIntent object only if your app needs to be notified
// that the user allowed the widget to be pinned. Note that, if the pinning
// operation fails, your app isn't notified.
val successCallback = PendingIntent.getBroadcast(
context,
0,
// Configure the intent so that your app's broadcast receiver gets
// the callback successfully. This callback receives the ID of the
// newly-pinned widget (EXTRA_APPWIDGET_ID).
Intent(context, TaskListWidgetPinnedReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val b = Bundle().apply {
val remoteViews = RemoteViews(context.packageName, R.layout.widget_configure_task_list)
putParcelable(AppWidgetManager.EXTRA_APPWIDGET_PREVIEW, remoteViews)
}
appWidgetManager.requestPinAppWidget(myProvider, b, successCallback)
}
@Ayush783
Copy link
Copy Markdown

Ok, Thanks for the info. Will look into it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment