我目前正在尝试将 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>
感谢您的帮助!
最佳答案
你的 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 ,如下所示:
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
关于java - RemoteViewsService 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364997/