Search code examples
androidbroadcastreceiverandroid-widgetandroid-appwidget

Android: enable/disable app widgets programmatically


Question: Is there a way to enable some of the homescreen widgets that I give out with my app programmatically? For example, having a "premium" widget and giving access to it only after payment?


As the Android docs say, one should add a broadcast receiver in the manifest to tell the system that there is a widget coming with the app:

<receiver android:name="ExampleAppWidgetProvider" >
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data android:name="android.appwidget.provider"
           android:resource="@xml/example_appwidget_info" />
</receiver>

But in theory broadcast receivers can also be added programmatically, so can the widgets be registered later at runtime?


Solution

  • You can have android:enabled="false" on the <receiver> element for the app widget in the manifest, then use PackageManager and setComponentEnabledSetting() to enable it at runtime when the the user does something (e.g., pay up).

    However, it is possible that this will require a reboot before the home screen realizes that there is a new potential app widget provider.