8

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?

frangulyan
  • 3,580
  • 4
  • 36
  • 64

2 Answers2

12

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks! A short question to it: does this mean that other apps can call this function specifying my receiver component or even enable it from adb command line? – frangulyan Oct 16 '16 at 18:47
  • @frangulyan: "does this mean that other apps can call this function specifying my receiver component" -- ordinary Android SDK apps cannot. System apps, apps on rooted devices, etc. might. "even enable it from adb command line?" -- I think so. IMHO, that should be fairly far down your list of concerns. – CommonsWare Oct 16 '16 at 18:53
  • 5
    Late to the party, I know, but for future reference `setComponentEnabledSetting()` doesn't reliably work for AppWidgets on all Android versions. Bug report is here: https://issuetracker.google.com/issues/36914010 – Sterling Sep 16 '17 at 20:21
  • 1
    not working.. on run time it does not enable receiver – Rishav Singla Jul 24 '19 at 11:46
  • @String Now the bug is fixed!! – kelvin Jul 21 '21 at 05:15
  • @kelvin do you have a reference for the fix? I still experience some issue, especially Android 11 and below. – Shareem Gelito Teofilo May 17 '23 at 21:38
5
PackageManager packageManager = getApplicationContext().getPackageManager();
//To disable widget
packageManager.setComponentEnabledSetting(new ComponentName(getApplicationContext(), MyAppWidgetProvider.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
//To enable widget
packageManager.setComponentEnabledSetting(new ComponentName(getApplicationContext(), MyAppWidgetProvider.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
thanhbinh84
  • 17,876
  • 6
  • 62
  • 69
Jithin Jude
  • 840
  • 14
  • 19