Enabling / Disabling activities at runtime

Written by Xavier Gouchet - 20 february 2013 - no comments

Sometimes, you might want an activity to be available only under specific conditions. But you may want to completely disable it at runtime when some conditions are met. For instance based on the time, or the user geolocation.

This could also let one have different activities based on the user's configuration

You can do so simply by using the PackageManager. In the following example, I disable an activity and enable another one.


PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(new ComponentName(this, ActivityC.class), 
    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
pm.setComponentEnabledSetting(new ComponentName(this, ActivityA.class), 
    PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);

The manifest declares the two activities with the same intent filter, namely the home screen shortcut. But using the previous code, I'm able to get a single one of them in the launcher menu at any given time.

Write a comment