Skip to content

Instantly share code, notes, and snippets.

@adityabhaskar
Created December 7, 2020 11:29
Show Gist options
  • Save adityabhaskar/9c1ba052d0ee2b3d9c9650f5f0c98490 to your computer and use it in GitHub Desktop.
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)
}
@DawnHNguyen
Copy link

Hi, thank you for sharing this code. I'm working on an widget app now. But it has some issue.

  • Firstly, on Redmi device, the successCallBack is never launch
  • Secondly, on Samsung S23 (Android 13), the EXTRA_APPWIDGET_PREVIEW is not shown. When I call requestPinAppWidget, it show the default previewImage from appwidget-provider
    Do you know what happen with my code. How can I debug/fix it. Thank you so much

@Ayush783
Copy link

Did you find a workaround @DawnHNguyen, Facing the same issue here. Thanks in advance

@DawnHNguyen
Copy link

@Ayush783 Unfortunately, I can't find any. For the first problem. I save the value I want to pass to the WidgetReceiver to LocalStorage (like DataStore), then in the WidgetReceiver, I get the value I pass, then do the stuff I want at there, instead of at successCallBack. For the second one, I discussed it again with the team and decided that I would use previewImage instead of EXTRA_APPWIDGET_PREVIEW. So that, none of these issue is fixed or workaround, I have to change how the code work

@Ayush783
Copy link

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