0

I'm having an issue with binding click events to an app widget with Xamarin Android. The clicks are working, and are launching the activity, but the information passed along to differentiate the widgets is not working. It appears that the same intent is being registered for all instances of the widget.

Below is a cut down sample of the code doing the click binding from a service. The full code also updates text on the widgets. That part is working fine, and is different on each instance of the widget, so I believe the overall update pattern is correct. That leaves me with the intent/pending intent binding as the problem. Is there something wrong with the pattern I'm using below?

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
    var manager = AppWidgetManager.GetInstance(this);
    var ids = intent.GetIntArrayExtra(AppWidgetManager.ExtraAppwidgetIds);

    foreach (var id in ids)
    {
        var widgetView = new RemoteViews(PackageName, Resource.Layout.SingleRateWidget);
        var activityIntent = new Intent(this, typeof(ExchangesActivity));
        activityIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
        activityIntent.PutExtra("WidgetId", id);
        var pendingIntent = PendingIntent.GetActivity(this, 0, activityIntent, PendingIntentFlags.UpdateCurrent);
        widgetView.SetOnClickPendingIntent(Resource.Id.widgetBackground, pendingIntent);
        manager.UpdateAppWidget(id, widgetView);
    }

    return StartCommandResult.Sticky;
}

Thanks.

StuffOfInterest
  • 518
  • 3
  • 11

1 Answers1

0

After more searching I found the fix in a question from Java Android development here:

Multiple Instances Of Widget Only Updating Last widget

Short answer, change the creation of the pending intent to this:

var pendingIntent = PendingIntent.GetActivity(this, id, activityIntent, PendingIntentFlags.UpdateCurrent);

Long answer, Android doesn't see a difference in the pending intent so it is reusing the same pending intent each time. Having an intent with PutExtra is not enough to differentiate the actions. By setting the requestCode to the widget ID there is something to make the pending intents unique. Another option is to do a SetData on the action intent with a unique URI (using the app widget id), but it is easier to just use the requestCode on the pending intent.

StuffOfInterest
  • 518
  • 3
  • 11