Created
December 7, 2020 11:29
-
-
Save adityabhaskar/9c1ba052d0ee2b3d9c9650f5f0c98490 to your computer and use it in GitHub Desktop.
Pinning an Android widget programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Did you find a workaround @DawnHNguyen, Facing the same issue here. Thanks in advance
@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
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
Hi, thank you for sharing this code. I'm working on an widget app now. But it has some issue.
successCallBack
is never launchEXTRA_APPWIDGET_PREVIEW
is not shown. When I callrequestPinAppWidget
, it show the defaultpreviewImage
fromappwidget-provider
Do you know what happen with my code. How can I debug/fix it. Thank you so much