Search code examples
javaandroidandroid-appwidgetappwidgetprovider

When exactly is AppWidgetProvider.onRestored() being called?


In which cases should i override onRestored?

Are they just referring to the backup which can be enabled/disabled in the manifest? Is it possible that this method get's called when the app get's updated too? Or under any other circumstances where the appWidgetIds might change? I think the ids are supposed to stay the same forever but not all manufacturers/launchers treat widgets the same way...

Could this be useful against phantom/ghost widgets?

/**
 * Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_RESTORED} broadcast
 * when instances of this AppWidget provider have been restored from backup.  If your
 * provider maintains any persistent data about its widget instances, override this method
 * to remap the old AppWidgetIds to the new values and update any other app state that may
 * be relevant.
 *
 * <p>This callback will be followed immediately by a call to {@link #onUpdate} so your
 * provider can immediately generate new RemoteViews suitable for its newly-restored set
 * of instances.
 *
 * {@more}
 *
 * @param context
 * @param oldWidgetIds
 * @param newWidgetIds
 */
public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
}

Solution

  • The onRestored() method is closely related to Android's backup/restore process.

    In Android, it is possible to backup/restore app data to Google Drive through BackupManagerService. At this time, when the backed up data is restored, the app widget data is also restored, and onRestored() is called when the restoration is complete.

    In addition, AppWidgetId is managed by uid, and it is seen in the form of increasing from 0. Since the id can be changed at the time of restoration, oldId and newId are delivered when onRestored() is called.

    The process for this can be traced in AppWidgetServiceImpl.java, and for an overview of the Android backup system, refer to the url below.

    https://developer.android.com/guide/topics/data/backup