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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With