【问题标题】:Use different actions for different widgets对不同的小部件使用不同的操作
【发布时间】:2014-07-13 22:06:41
【问题描述】:

在示例应用程序中,它执行 4 个动作,动作 1~4。我想让用户为每个不同的操作创建小部件按钮。当用户创建一个小部件时,配置活动允许用户选择一个操作。按下小部件应该执行操作。

问题在于,当为操作 1 创建一个小部件,然后为操作 2 创建另一个小部件时,操作 1 的小部件操作似乎被操作 2 的操作覆盖。也就是说,任何小部件都像最后一个小部件一样工作.我怎样才能解决这个问题?我已将完整项目上传至http://tempsend.com/E552810CFE(有效期至 2014 年 8 月 13 日)。

public class WidgetReceiver extends AppWidgetProvider
{
public WidgetReceiver()
{
}

private static final String WIDGET_BUTTON_CLICKED = "WidgetButtonClickedIntent";

@Override
public void onReceive(Context context, Intent intent)
{
    super.onReceive(context, intent);

    if (WIDGET_BUTTON_CLICKED.equals(intent.getAction()))
    {
        int actionID = intent.getIntExtra("ActionID", -1);
        Toast.makeText(context, "Doing action " + actionID, Toast.LENGTH_SHORT).show();
        Log.d("StackOverflow", "Doing action " + actionID);
    }
}

@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager,
                                      int appWidgetId, Bundle newOptions)
{
    int actionID;

    super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    Log.d("StackOverflow", "onAppWidgetOptionsChanged is called for " + appWidgetId);


    Bundle bun = appWidgetManager.getAppWidgetOptions(appWidgetId);
    actionID = bun.getInt("ActionID");
    Log.d("StackOverflow", "The action ID is " + actionID);


    RemoteViews remoteViews;
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_button);

    remoteViews.setTextViewText(R.id.textView, "Action " + actionID);
    remoteViews.setOnClickPendingIntent(R.id.textView,
            getPendingSelfIntent(context, WIDGET_BUTTON_CLICKED, actionID));

    appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}


@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    String ids = Arrays.toString(appWidgetIds);
    Log.d("StackOverflow", "onUpdate is called for " + ids);

}

protected PendingIntent getPendingSelfIntent(Context context, String action, int actionID)
{
    Intent intent = new Intent(context, getClass());
    intent.setAction(action);
    intent.putExtra("ActionID", actionID);

    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

}

【问题讨论】:

    标签: android widget configure


    【解决方案1】:

    我找到了一个解决方案,并且它奏效了。 Android widget not updating - has incorrect widget ID 第二个参数是“requestCode”,我认为它无关紧要,因为它的名字。根据答案,Pending Intent 需要是唯一的,所以我需要做任何事情来使其唯一,例如放置一个唯一的请求代码,在我的情况下是小部件 ID。 我不确定这是否是干净的解决方案。如果有人知道更好,正确的解决方案,请在此处添加。然后我会选择它作为答案。

    【讨论】:

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