Passing widget id to activity

2019-07-12 15:55发布

In my widget provider, I have the following code:

for (int widget_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?

4条回答
Explosion°爆炸
2楼-- · 2019-07-12 16:08

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-07-12 16:21

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.

查看更多
4楼-- · 2019-07-12 16:22

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

查看更多
▲ chillily
5楼-- · 2019-07-12 16:32

Try the following code instead:

if (extras != null) {
  int widget_id = getIntent().getIntExtra("widget_id", defaultValue);
}
查看更多
登录 后发表回答