3

我的主屏幕上有 2 个小部件。我知道如何从我的主要活动更新单个小部件。当我按下主活动上的后退按钮时,以下代码会更新我的单个小部件。

@Override
public void onBackPressed() {
    Intent intent = new Intent(this, todo_widget.class);
    intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
    int[] ids = AppWidgetManager.getInstance(getApplication())
            .getAppWidgetIds(
                    new ComponentName(getApplication(),         todo_widget.class));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
    sendBroadcast(intent);}

但是如果我这样写代码,两个小部件都不会更新:-

@Override
public void onBackPressed() {
    Intent intent = new Intent(this, todo_widget.class);
    intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
    int[] ids = AppWidgetManager.getInstance(getApplication())
            .getAppWidgetIds(
                    new ComponentName(getApplication(),     todo_widget.class));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
    sendBroadcast(intent);
    Intent intent1 = new Intent(this, todo_widget2.class);
    intent1.setAction("android.appwidget.action.APPWIDGET_UPDATE");
    int[] ids1 = AppWidgetManager.getInstance(getApplication())
            .getAppWidgetIds(
                    new ComponentName(getApplication(), todo_widget2.class));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids1);
    sendBroadcast(intent1);
    this.finish();
}

请有人帮我解决这个问题。当我按下后退按钮或创建我的主要活动时,如何更新两个小部件?

4

0 回答 0