2

我确定我遗漏了一些东西,但我只是想获得一个带有按钮和计数器的应用小部件。每次单击按钮时,我都希望计数器更新 1。

我已经设置了 WidgetProvider 的 onUpdate() 函数来向按钮注册一个挂起的事件,以便它启动一个服务来碰撞计数器 numbver:

Intent active = new Intent(context, CounterService.class);
active.setAction(CounterService.COUNT);
PendingIntent pending = PendingIntent.getService(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.CountButton, pending);

ComponentName component = new ComponentName(context.getPackageName(), KickCounterWidgetProvider.class.getName());    
appWidgetManager.updateAppWidget(component, views);

然后在服务 CounterService::onStart() 函数中,我增加了计数(暂时存储在 prefs 中),然后尝试更新显示当前计数值的文本字段:

// ... bump the count here and store a string representation of it in currentCountString ...

RemoteViews remoteView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.widget);

remoteView.setTextViewText(R.id.CurrentKickCount, currentCountString);

// apply changes to widget
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
ComponentName component = new ComponentName(getApplicationContext().getPackageName(), KickCounterWidgetProvider.class.getName());    
appWidgetManager.updateAppWidget(component, remoteView);

明智地使用 Logcat 表明这一切正常,字符串似乎没问题,但由于某种原因,对 appWidgetManager.updateAppWidget() 的调用似乎因某种原因默默地失败了。

我根本不知道它是否相关,但是当我第一次将小部件的实例添加到主屏幕时,甚至按钮都不起作用(即,Provider 中 onUpdate() 中对 updateAppWidget() 的调用失败)。小部件的后续实例似乎可以正常调用 Provider 中的 updateAppWidget() ,但不能用于服务。

任何帮助将不胜感激。

4

2 回答 2

6

来自: http ://code.google.com/p/android/issues/detail?id=8889

将小部件安装到新擦除或新创建的 AVD 上时,appWidgetManager.updateAppWidget 调用不会更新相应的
小部件。正确接收意图,正常调用调用,但没有发生小部件更新。

如果您重新启动 AVD(无论是否在设备上安装了小部件的软件包),在第一次非新初始化启动后问题将不复存在。

这个问题似乎存在于 2.0 和 2.1 上,在 1.5、1.6 和 2.2 上它的行为与预期一致。

于 2010-11-17T21:58:19.247 回答
0

您的一般方法似乎很合理,尽管this可能在getApplicationContext()这里也有效。不过,您最后的完整段落表明其他事情可能有问题。这是一个有点复杂的示例项目,它演示了您正在使用的那种模式——在这种情况下,随机选择一家餐厅而不是碰碰柜台。

于 2010-11-16T21:05:49.690 回答