重新输入活动后无法更新AppWidget RemoteViews

时间:2013-08-16 12:29:29

标签: android

当我在活动中更改了一些数据时,我试图在appwidget中手动更新我的ListView,当我第一次在手机上安装应用程序时,我可以成功完成。 但在我离开应用程序并再次重新输入后,我无法更新我的远程视图。

我调用AppWidgetUpdater来帮助我更新远程视图:

AppWidgetUpdater appWidgetUpdater = new AppWidgetUpdater(context);
appWidgetUpdater.updateAppWidget();

AppWidgetUpdater:

public void updateAppWidget(){
    ComponentName appWidget = new ComponentName(context, SimpleTODOAppWidgetProvider.class);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(appWidget);

    Intent intent = new Intent(context, SimpleTODOAppWidgetProvider.class);
    intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");

    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,appWidgetIds);
    context.sendBroadcast(intent);
}

的AppWidgetProvider:

public class SimpleTODOAppWidgetProvider extends AppWidgetProvider {

private Context context;
private AppWidgetManager appWidgetManager;
private int[] appWidgetIds;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    final int N = appWidgetIds.length;
    for (int i=0; i<N; i++) {       
        RemoteViews remoteViews = updateWidgetListView(context,
                appWidgetIds[i]);
        appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
        Log.d("TEST", appWidgetIds.toString() + " from provider");
    }   

}

@SuppressWarnings("deprecation")
private RemoteViews updateWidgetListView(Context context, int appWidgetId) {

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget_main);
    Intent svcIntent = new Intent(context, ListViewAdaptorService.class);
    svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
    remoteViews.setRemoteAdapter(appWidgetId, R.id.appwidget_listview,
            svcIntent);
    remoteViews.setEmptyView(R.id.appwidget_listview, R.id.appwidget_addbutton);

    return remoteViews;
}

}

1 个答案:

答案 0 :(得分:0)

最后我发现问题所在。 我应该使用:

appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.appwidget_listview);

而不是:

appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);

更新我的ListView。在AppWidget中使用Adapter之前,我应该做一些熟悉ListViewAdaptor的工作......