使用应用程序更新 ListView 小部件

Update ListView Widget with Application

当我尝试从我的应用程序更新内容时,我的应用程序小部件出现问题。我的小部件包含一个列表视图。

列表视图工作正常,每 30 分钟更新一次,但我在应用程序中进行更改时也需要更新它。这是我的代码:

public class WidgetListProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        ComponentName component;
        for (int i = 0; i < N; ++i) {
            RemoteViews remoteViews = updateWidgetListView(context,
                    appWidgetIds[i]);
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);

            component=new ComponentName(context,WidgetListProvider.class);
            appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listViewWidget);
            appWidgetManager.updateAppWidget(component, remoteViews);
        }

        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_list_layout);

        Intent svcIntent = new Intent(context, WidgetService.class);
        svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
        remoteViews.setRemoteAdapter(R.id.listViewWidget, svcIntent);
        remoteViews.setEmptyView(R.id.listViewWidget, R.id.empty_view);
        return remoteViews;
    }

}

I also need to update it when i make changes in the application

您可以随时通过静态 getInstance() 方法获得 AppWidgetManager。只要您跟踪需要更新的应用程序小部件 ID,当应用程序中的其他工作需要更新您的应用程序小部件内容时,您可以在很大程度上遍历现有代码。

将此代码放入您要更新内容的应用程序中。

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetIds[] = appWidgetManager.getAppWidgetIds(new ComponentName(context, WidgetListProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listViewWidget);