我确定我遗漏了一些东西,但我只是想获得一个带有按钮和计数器的应用小部件。每次单击按钮时,我都希望计数器更新 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() ,但不能用于服务。
任何帮助将不胜感激。