How to disable Activity and enable it programmatically?
In this example there are two activities declared in AndroidManifest.xml file. SetupActivity is enabled and MainActivity is disabled by default.
<activity
android:name=”.SetupActivity”
android:label=”@string/app_name_setup”
android:icon=”@drawable/app_setup_icon”
android:enabled=”true”>
<intent-filter>
<action android:name=”android.intent.action.MAIN”/>
<category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
<activity
android:name=”.MainActivity”
android:label=”@string/app_name”
android:icon=”@string/app_icon”
android:enabled=”false”>
<intent-filter>
<action android:name=”android.intent.action.MAIN”/>
<category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
You can enable MainActivity by using following code.
private void toggleActivities() {
PackageManager packageManager = getPackageManager();
// Enable the main activity
packageManager.setComponentEnabledSetting(new ComponentName(this, MainActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
// Disable the setup activity
packageManager.setComponentEnabledSetting(new ComponentName(this, SetupActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
Sometimes you have a component, usually a Service, that you don’t want to expose to the rest of the system for security purposes. To do this, you can set the android:exported attribute to false, which will effectively hide that component from the rest of the system.
<activity
android:name=”.SetupActivity”
android:label=”@string/app_name_setup”
android:icon=”@drawable/app_setup_icon”
android:enabled=”true”>
<intent-filter>
<action android:name=”android.intent.action.MAIN”/>
<category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
<activity
android:name=”.MainActivity”
android:label=”@string/app_name”
android:icon=”@string/app_icon”
android:enabled=”false”>
<intent-filter>
<action android:name=”android.intent.action.MAIN”/>
<category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
You can enable MainActivity by using following code.
private void toggleActivities() {
PackageManager packageManager = getPackageManager();
// Enable the main activity
packageManager.setComponentEnabledSetting(new ComponentName(this, MainActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
// Disable the setup activity
packageManager.setComponentEnabledSetting(new ComponentName(this, SetupActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
Sometimes you have a component, usually a Service, that you don’t want to expose to the rest of the system for security purposes. To do this, you can set the android:exported attribute to false, which will effectively hide that component from the rest of the system.
Comments
Post a Comment