我目前正在尝试向我的小部件添加ListView
。可悲的是,我的RemoteViewsService
没有被召唤。
这是我的小部件刷新代码:
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_today_layout);
Intent intent = new Intent(context, TodayWidgetService.class);
intent.putExtra("package", context.getPackageName());
intent.putExtra("items", items.toArray(new String[items.size()])); // items is just a List<String>
views.setRemoteAdapter(R.id.widget_today_content, intent);
manager.notifyAppWidgetViewDataChanged(ids, R.id.widget_today_content);
服务代码(TodayWidgetService
):
@Override
public RemoteViewsFactory onGetViewFactory(final Intent intent) {
System.out.println("Called");
return new TodayWidgetReceiver.WidgetFactory(intent.getStringExtra("package"), intent.getStringArrayExtra("items"));
}
如您所见,每次执行服务时都会打印一条Called
消息。这就是我在这里的原因:消息不在我的控制台中(因此,不调用该服务)。
我在AndroidManifest.xml
:
<application
...
<service
android:name="services.TodayWidgetService"
android:permission="android.permission.BIND_REMOTEVIEWS">
</service>
</application>
感谢您的帮助!
答案 0 :(得分:1)
你的onUpdate方法必须像这样:
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// update each of the app widgets with the remote adapter
for (int i = 0; i < appWidgetIds.length; ++i) {
// Set up the intent that starts the StackViewService, which will
// provide the views for this collection.
Intent intent = new Intent(context, StackWidgetService.class);
// Add the app widget ID to the intent extras.
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
// Instantiate the RemoteViews object for the app widget layout.
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
// Set up the RemoteViews object to use a RemoteViews adapter.
// This adapter connects
// to a RemoteViewsService through the specified intent.
// This is how you populate the data.
rv.setRemoteAdapter(R.id.stack_view, intent);
// The empty view is displayed when the collection has no items.
// It should be in the same layout used to instantiate the RemoteViews
// object above.
rv.setEmptyView(R.id.stack_view, R.id.empty_view);
//
// Do additional processing specific to this app widget...
//
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
请检查以下事项:
您是否在刷新代码中调用了appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
?
您需要将appWidgetId和数据设置为Service意图,如下所示:
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,appWidgetIds [i]); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
答案 1 :(得分:0)
我通过修复小部件布局解决了这个问题。确保为remote adapter
使用正确的组件。
在我的情况下,我使用了RelativeLayout
,将其替换为GridView