RemoteViewsFactory -> AppWidgetProvider
从 RemoteViewsFactory 到 AppWidgetProvider 的通信可以使用广播来完成,例如像这样:
Intent intent = new Intent(ACTION_PROGRESS_OFF);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
AppWidgetProvider 接收事件如下:
@Override
public void onReceive(final Context context, final Intent intent) {
// here goes the check if the app widget id is ours
final String action = intent.getAction();
if (ACTION_PROGRESS_OFF.equals(action)) {
// turn off the refresh spinner
当然广播动作需要在清单中定义:
<receiver
android:name="...">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="myPackage.ACTION_PROGRESS_OFF" />
</intent-filter>
<meta-data ... />
</receiver>
AppWidgetProvider->RemoteViewsFactory
与 RemoteViewsFactory 通信的一种方法(在您的情况下可能是最好的一种)是将您传递给 RemoteViewsAdapter 的服务意图中的信息发送:
Intent intentRVService = new Intent(context, RemoteViewsService.class);
intentRVService.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// let's put in some extra information we want to pass to the RemoteViewsFactory
intentRVService.putExtra("HELLO", "WORLD");
// when intents are compared, the extras are ignored, so we need to
// embed the extras into the data so that the extras will not be ignored
intentRVService.setData(Uri.parse(intentRVService.toUri(Intent.URI_INTENT_SCHEME)));
rv.setRemoteAdapter(appWidgetId, R.id.my_list, intentRVService);
rv.setEmptyView(R.id.my_list, android.R.id.empty);
// create the pending intent template for individual list items
...
rv.setPendingIntentTemplate(R.id.my_list, pendingIntentTemplate);
appWidgetMgr.notifyAppWidgetViewDataChanged(appWidgetId, R.id.my_list);
RemoteViewsService 可以轻松地从意图中检索信息并将其传递给 RemoteViewsService.RemoteViewsFactory。
我不是 100% 确定您的小部件决定何时以及如何对数据进行排序,但我假设如果用户选择要排序的列,那么您必须使用 notificationAppWidgetViewDataChanged 经历更新周期,然后您将传递该列。如果您稍后需要该信息,则必须以某种方式存储该信息(SharedPreferences)。