Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
frangulyan Avatar asked Oct 16 '16 12:10

frangulyan


2 Answers

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.

like image 194
CommonsWare Avatar answered Oct 23 '22 16:10

CommonsWare


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);
like image 32
Jithin Jude Avatar answered Oct 23 '22 16:10

Jithin Jude