androidandroid-intentandroid-widgetandroid-pendingintenthome-screen-widget

Receiving "old" Intent data from Widget PendingIntent. How to clear out?


My WidgetConfigActivity creates an onClickListener PendingIntent to pass through RemoteViews to perform two tasks: (1) open SliderActivity and (2) pass the appropriate appWidgetId.

val views =RemoteViews(context.packageName, R.layout.widget)
views.setOnClickPendingIntent(
    R.id.tv_widget_access_slider, 
    getSliderPendingIntent(this, appWidgetId)
)

fun getSliderPendingIntent(context: Context, appWidgetId: Int): PendingIntent {
    val intent =Intent(context, SliderActivity::class.java)
    intent.putExtra("appWidgetId", appWidgetId)
    intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)  //tried this but didn't help
    Log.d("APP WIDGET PENDING INTENT", "$appWidgetId")
    return PendingIntent.getActivity(
        context,
        0,
        intent,
        PendingIntent.FLAG_IMMUTABLE
    )
}

I need to get the appWidgetId in my SliderActivity so that the correct data can be displayed. So, I get the intent in onCreate.

val appWidgetId =intent.extras?.getInt("appWidgetId", 0) ?: 1
Log.d("APP WIDGET ID RECEIVED", "$appWidgetId")
intent.removeExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)   //tried this but didn't help

It works except for one thing. By logging, I've learned that the same appWidgetId is always received in SliderActivity onCreate even though unique appWidgetIds are added to the PendingIntent

First widget added to home screen Pending intent id =187, Slider onCreate id =187

Second widget added to home screen Pending intent id =188, Slider onCreate id =187

Third widget added to home screen Pending intent id =189, Slider onCreate id =187

How can I get the correct appWidgetId to my widget onClickListner to my SliderActivity?


Solution

  • Each distinct app widget needs a distinct PendingIntent, where "distinct" is largely determined by the ID that you pass as the second parameter to the PendingIntent.getActivity() method. If you use the same ID for multiple app widgets, they all wind up using the same PendingIntent, despite code that otherwise looks like it is creating three PendingIntent objects.

    If you need to change the contents of the Intent for a PendingIntent, use FLAG_UPDATE_CURRENT as part of your flags in the PendingIntent.getActivity() call. Otherwise, an existing PendingIntent for that ID will be left alone.

    IOW, think of PendingIntent.getActivity() as being a lazy-create mechanism — you need to take steps to force it to give you distinct objects and to update what is in them.