在示例应用程序中,它执行4个操作,操作1~4。我想让用户为每个不同的动作创建小部件按钮。当用户创建窗口小部件时,配置活动允许用户选择一个操作。按小部件应该执行操作。
问题在于,当创建Action 1的窗口小部件然后创建Action 2的窗口小部件时,Action 1的窗口小部件操作似乎被Action 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);
}
}
答案 0 :(得分:0)
我找到了解决方案并且有效。 Android widget not updating - has incorrect widget ID 第二个参数是“requestCode”,我认为因为它的名字而无关紧要。根据答案,Pending Intent需要是唯一的,因此我需要做任何事情以使其独特,例如放置一个唯一的请求代码,在我的例子中是小部件ID。 我不确定这是否是干净的解决方案。如果有人知道更好,更正确的解决方案,请在此处添加。然后我会选择它作为答案。