Ste*_*ven 6 android android-widget android-service stackview android-appwidget
我有一个包含StackView的AppWidget.与AppWidget一起,我有一个服务,当用户将我的AppWidget添加到他们的主屏幕时每两小时轮询一次新数据时启动该服务.当服务找到新数据时,我需要它提醒我的AppWidget,并将该数据传递给RemoteViewsService(具有我的RemoteViewsFactory),以便它可以为新数据创建必要的视图.
目前,当服务找到新数据时,我向AppWidget广播已发现新数据,将该数据作为意图内的整数数组传递.
我的AppWidgetProvider中的onReceive方法将该数据拉出来,然后我将完成设置一个新的intent的过程,该intent将传递给我的RemoteViews for AppWidget.示例代码如下:
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 );
}
Run Code Online (Sandbox Code Playgroud)
这是第一次工作.RemoteViewsService/RemoteViewsFactory显示数据.后续新数据未命中RemoteViewsFactory的构造函数,因为该工厂的服务已在运行.
我该如何更新数据?我觉得我应该使用onDataSetChanged,但是如何访问我从AppWidget的onReceive传递的意图?
我很欣赏任何关于如何妥善解决这个问题的见解.谢谢.
我使用BroadcastReceiver解决了传递给RemoteViewsFactory的整数数组的解决方案.我扩展了我的RemoteViewsFactory来实现BroadcastReceiver(特别是onReceive),并在工厂的构造函数中将我的应用程序注册到了它(这也意味着我在onDestroy中取消注册它).有了这个,我能够使用我在AppWidgetProvider的onReceive中的整数数组广播intent,并在RemoteViewsFactory中接收它.
确保还调用AppWidgetManager的notifyAppWidgetViewDataChanged,以便RemoteViewsFactory知道它之前使用的数据已经失效,并且提供了一个新的整数数组来创建新的RemoteViews.
| 归档时间: |
|
| 查看次数: |
2855 次 |
| 最近记录: |