我有一个 AppWidget,其中包含一个 StackView。除了 AppWidget,我还有一个服务,当用户将我的 AppWidget 添加到他们的主屏幕时,该服务会启动,每两个小时轮询一次新数据。当服务找到新数据时,我需要它提醒我的 AppWidget,并将该数据传递给 RemoteViewsService(它有我的 RemoteViewsFactory),以便它可以为新数据创建必要的视图。
目前,当服务找到新数据时,我让它向我的 AppWidget 广播已找到新数据,并将该数据作为意图中的整数数组传递。
我的 AppWidgetProvider 中的 onReceive 方法将数据拉出,然后我完成了设置新意图的过程,该意图传递给 AppWidget 的 RemoteViews。下面的示例代码:
public void onReceive( Context context, Intent intent )
{
int[] appWidgetIds = appWidgetManager.getAppWidgetIds( new ComponentName( context, SampleAppWidgetProvider.class ) );
int[] sampleData = intent.getIntArrayExtra( Intent.EXTRA_TITLE );
for ( int i = 0; i < appWidgetIds.length; i++ )
{
// RemoteViewsFactory service intent
Intent remoteViewsFactoryIntent = new Intent( context, SampleAppWidgetService.class );
remoteViewsFactoryIntent.putExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i] );
remoteViewsFactoryIntent.setData( Uri.parse( remoteViewsFactoryIntent.toUri( Intent.URI_INTENT_SCHEME ) ) );
remoteViewsFactoryIntent.putExtra( Intent.EXTRA_TITLE, sampleData );
RemoteViews rv = new RemoteViews( context.getPackageName(), R.layout.widget_layout );
// Sync up the remoteviews factory
rv.setRemoteAdapter( appWidgetIds[i], R.id.sample_widget, remoteViewsFactoryIntent );
rv.setEmptyView( R.id.sample_widget, R.id.empty_view );
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
super.onUpdate( context, appWidgetManager, appWidgetIds );
}
这是第一次。数据由 RemoteViewsService/RemoteViewsFactory 显示。随后的新数据不会命中 RemoteViewsFactory 的构造函数,因为该工厂的服务已经在运行。
我该如何更新数据?我觉得我应该使用 onDataSetChanged,但是如何访问我从 AppWidget 的 onReceive 传递的意图?
我将不胜感激有关如何正确处理此问题的任何见解。谢谢。