Updating app widget on orientation change

2019-08-05 09:36发布

问题:

I have an app with a main activity and an app widget. The app widget needs to be updated whenever the screen orientation changes (it computes its bitmap size and this depends on the current orientation).

How can I cause the widget to update on orientation change? I found the ACTION_CONFIGURATION_CHANGED event but am not sure how to use it since the documentation say that it cannot be registered in the manifest.

If it helps, I already have a BroadcastReciever that updates the widget on midnight.

回答1:

Answering my own question. The right way is not to detect orientation change (which may or may not used by the home launcher) but to have a widget that adapts automatically to orientation change. Sometimes it is trivial, sometimes it is not. In my case for example I needed to show one bitmap for landscape and one for portrait. Solved it by having two ImageViews, one that it is enable (by style resource) in portrait and the other in landscape. In AppWidgetProvider I populate the two images (file URI in my case) and let the launcher to pick the orientation it needs.

It is important to understand the upon device orientation change, the widget container recreates the layout (applying normal resource selection rules) and replay the RemoteViews commands on that layout.



回答2:

The solution was to use the onReceive() method to call onUpdate(). Here is my code:

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);  
    String action = intent.getAction();
    Toast.makeText(context, action, Toast.LENGTH_LONG).show();

    if (action.equals(action)) {
        Bundle extras = intent.getExtras();
        if (extras!=null) {
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            ComponentName thisAppWidget = new ComponentName(context.getPackageName(), WidNameWidgetActivity.class.getName());
            int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);
            onUpdate(context, appWidgetManager, appWidgetIds);
       }
    }
}