I’m creating a widget using Jetpack Glance in Android.
Creating widgets by long-clicking on the app icon is working well.
Here’s the scenario I’m trying to do.
- Inside my app, I have a PhotoListActivity.
- I can click on a specific photo to enter the PhotoDetailsActivity to view the details of that photo.
- I click the top right “Create Widget” button and the widget registration window pops up.
- click the “Add” button and the widget will be added to the home screen.
There are two BroadcastReceivers in the app.
- PhotoWidgetReceiver: This is a very simple GlanceAppWidgetReceiver.
- PhotoPinnedReceiver: This is a special purpose BroadcastReceiver that I added.
class PhotoWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = PhotoWidget()
}
@AndroidEntryPoint
class PhotoPinnedReceiver : BroadcastReceiver() {
@Inject
lateinit var widgetRepo: WidgetRepo
override fun onReceive(context: Context, intent: Intent) {
val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
if (widgetId == -1) {
Log.w(TAG, "onReceive - widgetId not exist")
return
}
val photoItem: PhotoItem? = intent.getParcelableExtra("photo_item")
if (PhotoItem == null) {
Log.w(TAG, "onReceive[$widgetId] photoItem is null")
return
}
Log.w(TAG, "onReceive[$widgetId] $photoItem")
CoroutineScope(Dispatchers.IO).launch {
widgetRepo.saveWidgetInfo(widgetId, photoItem)
PhotoWidget().updateAll(context)
}
}
companion object {
private const val TAG = "PhotoPinnedReceiver"
fun getPendingIntent(context: Context, photoItem: PhotoItem): PendingIntent {
val intent = Intent(context, PhotoPinnedReceiver::class.java)
.putExtra("photo_item", photoItem)
return PendingIntent.getBroadcast(
context,
0,
intent,
pendingIntentFlag(PendingIntent.FLAG_UPDATE_CURRENT, false)
)
}
}
}
In Step 3, When I clicked the top right “Create Widget” button on the PhotoDetailsActivity screen, the following code brings up the widget registration window.
val photoItem: PhotoItem = ... (my custom data class)
val appWidgetManager = AppWidgetManager.getInstance(this)
if (appWidgetManager.isRequestPinAppWidgetSupported) {
val widgetProvider = ComponentName(this, PhotoWidgetReceiver::class.java)
val successCallback = PhotoPinnedReceiver.getPendingIntent(this, photoItem)
appWidgetManager.requestPinAppWidget(widgetProvider, bundleOf("photo" to photoItem), successCallback)
}
But it just show empty ui.
Because, there are no data.
In PhotoPinnedReceiver, widgetId is not exist.
(I’ve shown the complete source code for the PhotoPinnedReceiver at the top.)
val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
In order to add a widget with one click of a button in the PhotoDetailsActivity, I need to store the widgetId and its photoItem in the WidgetRepository.
But I can’t figure out how to get these two values at the same time.
What should I do?