in BasicManagedProfile/Application/src/main/java/com/example/android/basicmanagedprofile/BasicManagedProfileFragment.java [212:254]
private void setAppEnabled(String packageName, boolean enabled) {
Activity activity = getActivity();
if (null == activity) {
return;
}
PackageManager packageManager = activity.getPackageManager();
DevicePolicyManager devicePolicyManager =
(DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
int packageFlags;
if(Build.VERSION.SDK_INT < 24){
//noinspection deprecation
packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
}else{
packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
}
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName,
packageFlags);
// Here, we check the ApplicationInfo of the target app, and see if the flags have
// ApplicationInfo.FLAG_INSTALLED turned on using bitwise operation.
if (0 == (applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED)) {
// If the app is not installed in this profile, we can enable it by
// DPM.enableSystemApp
if (enabled) {
devicePolicyManager.enableSystemApp(
BasicDeviceAdminReceiver.getComponentName(activity), packageName);
} else {
// But we cannot disable the app since it is already disabled
Log.e(TAG, "Cannot disable this app: " + packageName);
return;
}
} else {
// If the app is already installed, we can enable or disable it by
// DPM.setApplicationHidden
devicePolicyManager.setApplicationHidden(
BasicDeviceAdminReceiver.getComponentName(activity), packageName, !enabled);
}
Toast.makeText(activity, enabled ? R.string.enabled : R.string.disabled,
Toast.LENGTH_SHORT).show();
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "The app cannot be found: " + packageName, e);
}
}