Android: Widgets and multiple PendingIntent calls

It's been a while since I've blogged this, but I had an issue with PendingIntent when implementing widgets for Code Peeker Pro.

tldr version; The documentation doesn't make this clear, but when you're calling PendingIntent.getActivity(), the damn requestCode matters!

The widgets in Code Peeker allow you to create shortcuts to files on your phone. Each widget can point to a single file, which you choose upon creation of widget.

When initialising the widget, I set up PendingIntent on the view so it opens the appropriate file when tapped. In the majority of solutions on StackOverflow, I've seen "requestCode" be set to 0.

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// ...
views.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, views);

Now that's fine and dandy, until you have multiple widgets. Say for instance I have widget 1 which opens up file A, and widget 2 which opens up file B. Simple enough right?

NOPE! In my test cases, all widgets will open the same file, the most recently added one. In this case, both widgets 1 and 2 will only open file B. The PendingIntent is seemlingly shared across the widget views. Even after scouring the documentation, the notes for PendingIntent.getActivity() don't really raise any issues here either.

Only until I changed requestCode from "0" to the widget ID does this work properly. To infuriate me even further, the documentation previous said "currently not used" when describing the requestCode!!!

The new fix is just one arg change, "widgetID" in place of 0 for requestCode.

PendingIntent pendingIntent = PendingIntent.getActivity(context, widgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

tumblr_m3htpr2VBt1rqbr1po1_500
Google, Batman ain't got time for your bad docs!

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog