我有一个显示随机数的简单小部件。点击时它会刷新并显示另一个随机数。这是 AppWidgetProvider 的 onUpdate 方法的代码
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int widgetId : appWidgetIds) {
int number = new Random().nextInt(100);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_exchange);
remoteViews.setTextViewText(R.id.widget_textview, String.valueOf(number));
// Register an onClickListener
Intent intent = new Intent(context, ExchangeWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {widgetId} );
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, widgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.widget_textview, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
有了这个,小部件会在放置时进行第一次更新,但在单击时不会再次更新。如果我只是将挂起的意向行从:
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, widgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
到
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, widgetId, intent, 0);
即唯一改变的是最后一个参数现在是“0”
它现在按预期工作,点击它会显示一个新的随机数。
为什么它可以工作,但当它有 FLAG_UPDATE_CURRENT 标志时却不工作?
最佳答案
注意 PendingIntent 中的文档:
/**
* Flag indicating that if the described PendingIntent already exists,
* then keep it but replace its extra data with what is in this new
* Intent. For use with {@link #getActivity}, {@link #getBroadcast}, and
* {@link #getService}. <p>This can be used if you are creating intents where only the
* extras change, and don't care that any entities that received your
* previous PendingIntent will be able to launch it with your new
* extras even if they are not explicitly given to it.
*/
public static final int FLAG_UPDATE_CURRENT = 1<<27;
这意味着设置 FLAG_UPDATE_CURRENT
并不意味着更新广播监听器,而是更新挂起的 Intent (如果存在)。在您的情况下,它不存在,因此会被忽略。
关于android - 使用标志 FLAG_UPDATE_CURRENT 时,小部件 onclick 未决 Intent 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28564635/