问题
I have an app with several activities, they all have a launch intent-filter in the manifest so they can show several icons on the launcher, there is a main activity and the rest of them are disabled by default with android:enabled="false"
here is a part of my manifest:
<activity
android:name="com.myapp.MainActivity"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.myapp.Activity_1"
android:icon="@mipmap/ic_launcher"
android:label="@string/secondary_activity"
android:enabled="false">// HERE I DISABLE THE ACTIVITY
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
I found a way to enable or disable the other activities using the following code:
public static void enableComponent(Context context, Class<?> componentClass, boolean isEnable) {
int enableFlag = isEnable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
context.getPackageManager().setComponentEnabledSetting(new ComponentName(context, componentClass), enableFlag, PackageManager.DONT_KILL_APP);
}
private void setupDetailsOverviewRowPresenter() {
detailsPresenter.setOnActionClickedListener(new OnActionClickedListener() {
@Override
public void onActionClicked(Action action) {
if (action.getId() == ACTION_ENABLE){
mSelectedApp = (App) getActivity().getIntent().getSerializableExtra(DetailsActivity.APP);
enableComponent(mContext, com.myapp.Activity_1.class, true);
}
}else if (action.getId() == ACTION_DISABLED){
mSelectedApp = (App) getActivity().getIntent().getSerializableExtra(DetailsActivity.APP);
enableComponent(mContext, com.myapp.Activity_1.class, false);
}
}
});
}
This works perfectly by enabling or disabling the activity with the ACTION_ENABLE
or ACTION_DISABLE
buttons, but that's not good for usability, instead I would like to use just one button to enable or disable the activity.
What I need to know is how to get the status of the activity, so if the activity is android:enabled="false"
display the button with ACTION_EANBLE
and if the activity is android:enabled="true"
display the button with ACTION_DISABLE
.
回答1:
You can query the PackageManager
to determine if a component is enabled or not:
PackageManager pm = getPackageManager();
ComponentName cn = new ComponentName(...);
ActivityInfo info = pm.getActivityInfo(cn, 0);
if (info != null && info.enabled) {
// Component is enabled
...
} else {
// Component is disabled
...
}
来源:https://stackoverflow.com/questions/40975139/enable-or-disable-launch-intent-filter-activities-with-one-button