Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable and disable a component?

Tags:

android

My initial question was basically something along the lines of this: Clearing and setting the default home application

That question was answered to my satisfaction, however, the thing I'm having difficulty understanding in the answer is how do you enable and then disable a component from the manifest in the java code?

like image 389
scibor Avatar asked Jul 01 '13 17:07

scibor


People also ask

Which method do you use to enable/disable components?

You can disable the component by pressing Shift + D , too.


2 Answers

By using package manager you can enable or disable component declared in manifest file There are two flag PackageManager.COMPONENT_ENABLED_STATE_DISABLED for disable component and PackageManager.COMPONENT_ENABLED_STATE_ENABLED for enable component.

PackageManager pm = getApplicationContext().getPackageManager();
ComponentName componentName = new ComponentName("com.app",
    ".broadcast_receivers.OnNetworkChangedReceiver");
pm.setComponentEnabledSetting(componentName,
    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
    PackageManager.DONT_KILL_APP);

Android manifest:

<receiver
  android:name=".broadcast_receivers.OnNetworkChangedReceiver"
  android:enabled="true"
>
  <intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
  </intent-filter>
</receiver>

Official documentation: setComponentEnabledSetting

like image 191
Pawan Yadav Avatar answered Oct 18 '22 10:10

Pawan Yadav


taking Pawan approach to more generic implementation:

public static void setComponentState(Context context, String packageName , String componentClassName, boolean enabled)
{
    PackageManager pm  = context.getApplicationContext().getPackageManager();
    ComponentName componentName = new ComponentName(packageName, componentClassName);
    int state = enabled ?  PackageManager.COMPONENT_ENABLED_STATE_ENABLED :  PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
    pm.setComponentEnabledSetting(componentName,
            state,
            PackageManager.DONT_KILL_APP);

}
like image 33
Noam Segev Avatar answered Oct 18 '22 08:10

Noam Segev