Wednesday, April 4, 2012

Yet Another Dumb Widget Hiding Trick

I didn't mean to be writing a series of these articles, but I keep getting backed into a corner...

The last two times, I was dealing solely with preventing app widgets from appearing on particular versions of Android.  The problem is that this trick only works for platform version; all other resource qualifiers (like screen size) are ignored.

This becomes a problem when you have a widget that you only want to work on smaller screen sizes, or only in some locales, etc.  In this situation, you can't use the AndroidManifest tricks because all those values can change at runtime.

The hackiest answer I found was to manually disable the widget provider on launch, based on whatever parameters you provide.  In this case, I'm using a boolean I've defined as "widgetEnabled":

public class ExpediaBookingApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        if (getResources().getBoolean(R.bool.widgetEnabled)) {
            PackageManager pm = getPackageManager();
            ComponentName cn = new ComponentName(this, AppWidgetProvider.class);
            pm.setComponentEnabledSetting(cn, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        }
    }
}

This will only disable the widget after the first launch of the application, so it's still possible for users to install the widget before the first launch.  But it's way better than nothing.  Also note that this doesn't seem to work on every version of Android (but it does work on ICS, which is what I was targeting).

The true answer to this problem is to make sure your widget works on all platforms of Android.  But if you're squeezed this hack can save the day as well.

No comments:

Post a Comment