53

I created a widget that when clicked activates a PendingIntent. The problem is when I have more than one widget on the screen only the latest one will start the PendingIntent.

I have read some about a unique request code, but not figured this out.

Any ideas how I can have multiple widgets and the PendingIntents work for each?

Here is a snippet of my code:

Intent openApp = new Intent(context, RunningTally.class);
    openApp.putExtra("widgetId", appWidgetId);
    PendingIntent pendingAppIntent = 
        PendingIntent.getActivity(context, 0, openApp, PendingIntent.FLAG_CANCEL_CURRENT  );
    views.setOnClickPendingIntent(R.id.openFull, pendingAppIntent);
Cœur
  • 37,241
  • 25
  • 195
  • 267
taraloca
  • 9,077
  • 9
  • 44
  • 77

1 Answers1

116

So happens that after posting my question, I came up with an answer. I pass in my appWidgetId as the "unique" request code and voila! Here is the snippet now:

Intent openApp = new Intent(context, RunningTally.class);
    openApp.putExtra("widgetId", appWidgetId);
    PendingIntent pendingAppIntent = 
        PendingIntent.getActivity(context, appWidgetId, openApp, 
                                  PendingIntent.FLAG_CANCEL_CURRENT);
    views.setOnClickPendingIntent(R.id.openFull, pendingAppIntent);
Arlaharen
  • 3,095
  • 29
  • 26
taraloca
  • 9,077
  • 9
  • 44
  • 77
  • 24
    The worst is that the documentation says: requestCode Private request code for the sender (currently not used). So I saw it, but I didn't try to use it because I thought it wouldn't work! – thiagolr Sep 13 '12 at 18:37
  • @thiagolr right without passing extra it wont work , eventhough u have pass same unique value in pending intent, +1 for it – dharmendra Apr 01 '13 at 07:08
  • 5
    Of note - it is not marked _currently not used_ anymore http://developer.android.com/reference/android/app/PendingIntent.html#getBroadcast(android.content.Context,%20int,%20android.content.Intent,%20int) – Mr_and_Mrs_D Nov 14 '13 at 18:37
  • 2
    As i've noticed, this should work for any type of pending intent (including those of notifications). i think it's best to put a class that manages all of the types you have, to avoid overriding of them. – android developer Mar 05 '14 at 09:22
  • 3
    The key here is UNIQUE request code. If you pass two of the same - one will not work. – rickythefox Jul 03 '14 at 07:35
  • 1
    @android-developer yeah The concept of multiple instances of pending intent with different request codes works perfectly with `AlarmManager` too – johnkarka Aug 07 '15 at 19:53
  • Note: requestCode is useless for getBroadcast() type PendingIntent http://stackoverflow.com/a/33203752/2301224 – Baker Oct 19 '15 at 05:56
  • I had two buttons so I used: int requestCode = (int)(Math.random() * 100); – Chris B Apr 12 '16 at 04:26