AppWidgetProvider - Is onUpdate triggered every ti

2019-03-04 02:55发布

问题:

I am wondering about the onUpdate method. I know that it is called the first time a widget is placed on the homescree, and then period in the time I defined in the appwidget info xml file. But it seems as if this method is also called whenver I make changes to my AppWidgetProvider class, ie. adding or removing method. Is that observation correct? I don't understand how this triggers the onUpdate method?

public class ExampleAppWidgetProvider extends AppWidgetProvider {

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for (int appWidgetId : appWidgetIds) {
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
        String buttonText = prefs.getString(KEY_BUTTON_TEXT + appWidgetId, "Press me");

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.example_widget);
        views.setOnClickPendingIntent(R.id.example_widget_button, pendingIntent);
        views.setCharSequence(R.id.example_widget_button, "setText", buttonText);

        Bundle appWidgetOptions = appWidgetManager.getAppWidgetOptions(appWidgetId);
        resizeWidget(appWidgetOptions, views);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

回答1:

But it seems as if this method is also called whenver I make changes to my AppWidgetProvider class, ie. adding or removing method

The behavior here may be up to the implementation of the home screen or other app widget host. However, yes, your onUpdate() method may be invoked if you install a different edition of your app, which includes changes during development.

I don't understand how this triggers the onUpdate method?

Well, Android is an operating system. It knows when apps get installed and updated. I can see where an AppWidgetHost is notified, via onProviderChanged(), when the APK for an app widget provider changed. It is fairly reasonable that the OS code behind AppWidgetManager might also send a broadcast to get the AppWidgetProvider to deliver a fresh RemoteViews. Or, the home screen itself might be able to request a refresh, when it gets called with onProviderChanged().