I got a Widget on my HomeScreen on which i add an click to a Button. I pass the widget id from the Widget to a Service, but when im reading the WidgetId at the Service it's always 3.
Widget:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent intent = new Intent(context, WidgetService.class);
// prints the correct appWidgetId
System.out.println(appWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
remoteView.setOnClickPendingIntent(R.id.Button01, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteView);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
The Service looks like this:
public int onStartCommand(Intent intent, int flags, int startId){
if (intent != null && intent.getExtras() != null) {
int widgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
// 3 is always printend
System.out.println(widgetId);
// More stuff here
}
return super.onStartCommand(intent, flags, startId);
}
So what am I doing wrong?
What you're trying to do will not work, AFAIK, without some trickery.
There can be only one outstanding PendingIntent
per Intent
. So, if you create two Intents
that are equivalent (match on non-extra data), and you try to create two PendingIntents
, you really wind up with a single PendingIntent
in the end. Which Intent
is used depends a bit on the flags you supply to getService()
(or getActivity()
or getBroadcast()
). In your case, the first Intent
will always be used.
If you only had one outstanding PendingIntent
but just wanted to update its extras, FLAG_UPDATE_CURRENT
would work. But, you want N outstanding PendingIntents
.
The only way I know of to make that work in your case is to put a unique action string in the Intent
. Since you are specifying the component (WidgetService.class
), the action string will not be used for routing. However, it will suffice to give you multiple PendingIntent
objects.
Just to add to the comment above, see this example for how to make your intent unique: http://developer.android.com/resources/samples/StackWidget/src/com/example/android/stackwidget/StackWidgetProvider.html It seems like a really dumb design and an even worse workaround, but I guess that's the way it is. It took me a long time to find the simple example above. Pay particular attention to the intent.setData(Uri) call. I cut and pasted those lines into my onUpdate() method and it finally worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With