【问题标题】:Widget onclick pending intent doesn't fire when using flag FLAG_UPDATE_CURRENT使用标志 FLAG_UPDATE_CURRENT 时,小部件 onclick 挂起意图不会触发
【发布时间】:2015-04-18 08:00:46
【问题描述】:

我有一个显示随机数的简单小部件。当点击它刷新并显示另一个随机数。这是 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 标志时它不起作用?

【问题讨论】:

    标签: android android-intent android-widget


    【解决方案1】:

    注意来自 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 并不意味着更新广播侦听器,而是更新挂起的意图(如果存在)。在您的情况下,它不存在,因此会被忽略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      相关资源
      最近更新 更多