开发者

Passing widget id to activity

In my widget provider, I have the following code:

for (int wid开发者_开发技巧get_id : appWidgetIds) {
  Log.d(TAG, "Widget Id: " + widget_id);
  RemoteViews remoteViews;

  Widget widget;

  while (true) {
    try {
      widget = Widget.load(context, Widget.class, widget_id);
      break;
    }
    catch (Exception ex) {
      Log.e(TAG, "Exception!", ex);
    }
  }

  // Widget is assigned to user
  if (widget != null) {
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_with_user);
    remoteViews.setCharSequence(R.id.user_text, "setText", widget.user.name);
    remoteViews.setUri(R.id.avatar, "setImageURI", Uri.parse(widget.user.avatar));
  }
  else {
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
    Intent configIntent = new Intent(context, ConfigureWidget.class);
    configIntent.setAction(ACTION_WIDGET_CONFIGURE);
    configIntent.putExtra("widget_id", widget_id);

    PendingIntent configPendingIntent = PendingIntent.getActivity(context, REQUEST_CODE_ONE, configIntent, 0);
    remoteViews.setOnClickPendingIntent(R.id.configure_text, configPendingIntent);
  }

  appWidgetManager.updateAppWidget(widget_id, remoteViews);
}

In the else section, I'm launching a configuration activity and trying to pass the widget id to it. However, the bundle is always null:

Bundle extras = getIntent().getExtras();

if (extras != null) {
  int widget_id = extras.getInt("widget_id");
}

How can I get the widget id to the launched activity?


The issue was that android does caching with PendingIntents. The solution was to add the FLAG_UPDATE_CURRENT flag which causes it to update the cached PendingIntent.

PendingIntent configPendingIntent = PendingIntent.getActivity(context, REQUEST_CODE_ONE, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Source


Try the following code instead:

if (extras != null) {
  int widget_id = getIntent().getIntExtra("widget_id", defaultValue);
}


Did you make sure to properly register the intent filter in your manifest? For some reason, extras don't get passed properly without an explicit action, and it might not be working right if you haven't setup the intent filter.


public Bundle getExtras ()
Retrieves a map of extended data from the intent.

Source

Same goes for Intent.putExtra(Bundle). These are extended attributes.
Try using getIntent().getIntExtra(String key, int defaultValue) instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜