Skip to content

Instantly share code, notes, and snippets.

@sdecima
Created December 18, 2013 17:01
Show Gist options
  • Save sdecima/8025879 to your computer and use it in GitHub Desktop.
Save sdecima/8025879 to your computer and use it in GitHub Desktop.
How to dynamically enable/disable an Android Component declared in the manifest.
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
public class Android_enableManifestComponent {
public static void enableManifestComponent(Context context, Class<?> component, boolean enable) {
ComponentName receiver = new ComponentName(context, component);
PackageManager pm = context.getPackageManager();
int newState = (enable ?
PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
pm.setComponentEnabledSetting(receiver, newState,
PackageManager.DONT_KILL_APP);
}
}
@Radiokot
Copy link

Great snippet. I use it as a Kotlin Context extension:

import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager

/**
 * Explicitly enables or disables the given app component
 * such as a service or receiver without killing the app.
 *
 * @param componentClass the class of the desired component
 * @param isEnabled whether to enable or disable the component
 *
 * @see PackageManager.setComponentEnabledSetting
 * @see PackageManager.COMPONENT_ENABLED_STATE_ENABLED
 * @see PackageManager.COMPONENT_ENABLED_STATE_DISABLED
 */
fun Context.setManifestComponentEnabled(
    componentClass: Class<*>,
    isEnabled: Boolean,
) {
    packageManager.setComponentEnabledSetting(
        ComponentName(this, componentClass),
        if (isEnabled)
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED
        else
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP,
    )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment