下面列出了怎么用android.app.admin.DevicePolicyManager的API类实例代码及写法,或者点击链接到github查看源代码。
private void specifyDefaultDisclaimers(Intent intent) {
if (Util.SDK_INT >= VERSION_CODES.O) {
Bundle emmBundle = new Bundle();
emmBundle.putString(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_HEADER,
getString(R.string.default_disclaimer_emm_name));
emmBundle.putParcelable(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_CONTENT,
resourceToUri(getActivity(), R.raw.emm_disclaimer));
Bundle companyBundle = new Bundle();
companyBundle.putString(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_HEADER,
getString(R.string.default_disclaimer_company_name));
companyBundle.putParcelable(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMER_CONTENT,
resourceToUri(getActivity(), R.raw.company_disclaimer));
intent.putExtra(DevicePolicyManager.EXTRA_PROVISIONING_DISCLAIMERS,
new Bundle[] { emmBundle, companyBundle });
}
}
/**
* @return If the certificate was successfully installed.
*/
public static boolean installCaCertificate(InputStream certificateInputStream,
DevicePolicyManager dpm, ComponentName admin) {
try {
if (certificateInputStream != null) {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int len = 0;
while ((len = certificateInputStream.read(buffer)) > 0) {
byteBuffer.write(buffer, 0, len);
}
return dpm.installCaCert(admin,
byteBuffer.toByteArray());
}
} catch (IOException e) {
Log.e(TAG, "installCaCertificate: ", e);
}
return false;
}
@TargetApi(VERSION_CODES.N)
private void loadPasswordCompliant() {
Preference passwordCompliantPreference = findPreference(PASSWORD_COMPLIANT_KEY);
if (!passwordCompliantPreference.isEnabled()) {
return;
}
String summary;
boolean compliant = mDevicePolicyManager.isActivePasswordSufficient();
if (Util.isManagedProfileOwner(getActivity())) {
DevicePolicyManager parentDpm
= mDevicePolicyManager.getParentProfileInstance(mAdminComponentName);
boolean parentCompliant = parentDpm.isActivePasswordSufficient();
summary = String.format(getString(R.string.password_compliant_profile_summary),
Boolean.toString(parentCompliant), Boolean.toString(compliant));
} else {
summary = String.format(getString(R.string.password_compliant_summary),
Boolean.toString(compliant));
}
passwordCompliantPreference.setSummary(summary);
}
private String statusCodeToString(int newStatusCode) {
int newStatus = R.string.encryption_status_unknown;
switch (newStatusCode) {
case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
newStatus = R.string.encryption_status_unsupported;
break;
case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
newStatus = R.string.encryption_status_inactive;
break;
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
newStatus = R.string.encryption_status_activating;
break;
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
newStatus = R.string.encryption_status_active;
break;
}
return mActivity.getString(newStatus);
}
/**
* Enables forwarding of share intent between private account and managed profile.
*/
private void enableForwarding() {
Activity activity = getActivity();
if (null == activity || activity.isFinishing()) {
return;
}
DevicePolicyManager manager =
(DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
IntentFilter filter = new IntentFilter(Intent.ACTION_SEND);
filter.addDataType("text/plain");
filter.addDataType("image/jpeg");
// This is how you can register an IntentFilter as allowed pattern of Intent forwarding
manager.addCrossProfileIntentFilter(BasicDeviceAdminReceiver.getComponentName(activity),
filter, FLAG_MANAGED_CAN_ACCESS_PARENT | FLAG_PARENT_CAN_ACCESS_MANAGED);
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
}
/**
* Returns true if the user switcher should be shown, this will be if device supports multi-user
* and there are at least 2 users available that are not managed profiles.
* @hide
* @return true if user switcher should be shown.
*/
public boolean isUserSwitcherEnabled() {
if (!supportsMultipleUsers()) {
return false;
}
if (hasUserRestriction(DISALLOW_USER_SWITCH)) {
return false;
}
// If Demo Mode is on, don't show user switcher
if (isDeviceInDemoMode(mContext)) {
return false;
}
List<UserInfo> users = getUsers(true);
if (users == null) {
return false;
}
int switchableUserCount = 0;
for (UserInfo user : users) {
if (user.supportsSwitchToByUser()) {
++switchableUserCount;
}
}
final boolean guestEnabled = !mContext.getSystemService(DevicePolicyManager.class)
.getGuestUserDisabled(null);
return switchableUserCount > 1 || guestEnabled;
}
private void loadSystemValues(HashMap<String, String> values) {
Context context = getContext();
//noinspection deprecation
putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME,
"com.example.android.deviceowner");
if (Build.VERSION.SDK_INT >= 23) {
putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME,
"com.example.android.deviceowner/.DeviceOwnerReceiver");
}
putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_LOCALE,
CompatUtils.getPrimaryLocale(context.getResources().getConfiguration()).toString());
putIfMissing(values, DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE,
TimeZone.getDefault().getID());
if (!values.containsKey(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID)) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Activity.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
if (info.getNetworkId() != -1) { // Connected to network
values.put(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID,
trimSsid(info.getSSID()));
}
}
}
/**
* Enables forwarding of share intent between private account and managed profile.
*/
private void enableForwarding() {
Activity activity = getActivity();
if (null == activity || activity.isFinishing()) {
return;
}
DevicePolicyManager manager =
(DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
IntentFilter filter = new IntentFilter(Intent.ACTION_SEND);
filter.addDataType("text/plain");
filter.addDataType("image/jpeg");
// This is how you can register an IntentFilter as allowed pattern of Intent forwarding
manager.addCrossProfileIntentFilter(BasicDeviceAdminReceiver.getComponentName(activity),
filter, FLAG_MANAGED_CAN_ACCESS_PARENT | FLAG_PARENT_CAN_ACCESS_MANAGED);
} catch (IntentFilter.MalformedMimeTypeException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
/*
if (v == lock) {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
*/
if (v == enable) {
Logd(TAG, "Attempting to enable admin");
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "ODM requires admin access for locking and wiping the device.");
startActivityForResult(intent, RESULT_ENABLE);
}
}
private void gatherAdminExtras(HashMap<String, String> values) {
Properties props = new Properties();
Set<String> keys = new HashSet<>(values.keySet());
for (String key : keys) {
if (key.startsWith("android.app.extra")) {
continue;
}
props.put(key, values.get(key));
values.remove(key);
}
StringWriter sw = new StringWriter();
try{
props.store(sw, "admin extras bundle");
values.put(DevicePolicyManager.EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE,
sw.toString());
Log.d(TAG, "Admin extras bundle=" + values.get(
DevicePolicyManager.EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE));
} catch (IOException e) {
Log.e(TAG, "Unable to build admin extras bundle");
}
}
@Override
public void clearPassword(Operation operation) {
operation.setStatus(getContextResources().getString(R.string.operation_value_completed));
getResultBuilder().build(operation);
getDevicePolicyManager().setPasswordQuality(getCdmDeviceAdmin(),
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
getDevicePolicyManager().setPasswordMinimumLength(getCdmDeviceAdmin(), getDefaultPasswordLength());
getDevicePolicyManager().resetPassword(getContextResources().getString(R.string.shared_pref_default_string),
DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
getDevicePolicyManager().lockNow();
getDevicePolicyManager().setPasswordQuality(getCdmDeviceAdmin(),
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
if (Constants.DEBUG_MODE_ENABLED) {
Log.d(TAG, "Password cleared");
}
}
@Override
public void onLoadFinished(Loader<Map<String, String>> loader, Map<String, String> values) {
if (loader.getId() == LOADER_PROVISIONING_VALUES) {
mProvisioningValues = values;
//noinspection deprecation
mEditPackageName.setText(values.get(
DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME));
if (Build.VERSION.SDK_INT >= 23) {
ComponentName name = ComponentName.unflattenFromString(values.get(
DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME));
mEditClassName.setText(name.getClassName());
}
mEditLocale.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_LOCALE));
mEditTimezone.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_TIME_ZONE));
mEditWifiSsid.setText(values.get(DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SSID));
mEditWifiSecurityType.setText(values.get(
DevicePolicyManager.EXTRA_PROVISIONING_WIFI_SECURITY_TYPE));
mEditWifiPassword.setText(values.get(
DevicePolicyManager.EXTRA_PROVISIONING_WIFI_PASSWORD));
}
}
/**
* Attempts to grant a permission automatically if it is considered dangerous - this only happens
* for PO/DO devices.
*/
@RequiresApi(VERSION_CODES.M)
private static boolean maybeGrantDangerousPermission(String permission, ComponentName admin,
Context context) {
if (!isPermissionDangerous(permission, context)) {
return true;
}
if (!ProvisioningStateUtil.isManagedByTestDPC(context)) {
return false;
}
if (hasPermissionGranted(admin, context, permission)) {
return true;
}
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context
.getSystemService(Context.DEVICE_POLICY_SERVICE);
return devicePolicyManager.setPermissionGrantState(
admin,
context.getPackageName(),
permission,
DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED);
}
@TargetApi(VERSION_CODES.O)
static List<DelegationScope> defaultDelegationScopes(boolean showDoOnlyDelegations) {
List<DelegationScope> defaultDelegations = new ArrayList<>();
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_CERT_INSTALL));
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_APP_RESTRICTIONS));
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL));
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_PERMISSION_GRANT));
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_PACKAGE_ACCESS));
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP));
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_CERT_SELECTION));
if (showDoOnlyDelegations) {
defaultDelegations.add(
new DelegationScope(DevicePolicyManager.DELEGATION_NETWORK_LOGGING));
}
return defaultDelegations;
}
/**
* Locks the device (and turns screen off).
*
* @return {@code true} if successful, {@code false} otherwise.
* @see DevicePolicyManager#lockNow()
*/
public boolean lock() {
DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
// TODO: Respect secure lock timeout settings.
mUnlockingTime = 0;
dpm.lockNow();
return true;
} catch (SecurityException e) {
String errorMessage = "Failed to lock the screen due to a security exception.";
ToastUtils.showLong(this, errorMessage);
Log.e(TAG, errorMessage);
// Clear the FLAG_KEEP_SCREEN_ON flag to prevent the situation when
// AcDisplay stays forever on. Normally this should never happen.
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
return false; // Screw you owner!
}
}
/**
* Sets the persistent device owner state by setting a special app restriction on GmsCore and
* notifies GmsCore about the change by sending a broadcast.
*
* @param state The device owner state to be preserved across factory resets. If null, the
* persistent device owner state and the corresponding restiction are cleared.
*/
@TargetApi(VERSION_CODES.O)
public static void setPersistentDoStateWithApplicationRestriction(
Context context, DevicePolicyManager dpm, ComponentName admin, String state) {
Bundle restrictions = dpm.getApplicationRestrictions(admin, GMSCORE_PACKAGE);
if (state == null) {
// Clear the restriction
restrictions.remove(PERSISTENT_DEVICE_OWNER_STATE);
} else {
// Set the restriction
restrictions.putString(PERSISTENT_DEVICE_OWNER_STATE, state);
}
dpm.setApplicationRestrictions(admin, GMSCORE_PACKAGE, restrictions);
Intent broadcastIntent = new Intent(BROADCAST_ACTION_FRP_CONFIG_CHANGED);
broadcastIntent.setPackage(GMSCORE_PACKAGE);
broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
context.sendBroadcast(broadcastIntent);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDpm = (DevicePolicyManager) getContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
if (Util.hasDelegation(getActivity(), DevicePolicyManager.DELEGATION_PERMISSION_GRANT)) {
mAdminComponent = null;
} else {
mAdminComponent = DeviceAdminReceiver.getComponentName(getContext());
}
}
@Test
public void ensureRequiredPermissions_ifPermissionIsDangerousAndDpcIsDeviceOwner_shouldReturnTrueAndSetPermissionGrantState() {
addPermissionInfo(DANGEROUS_PERMISSION, PermissionInfo.PROTECTION_DANGEROUS);
shadowOf(mDevicePolicyManager).setDeviceOwner(TESTDPC_ADMIN);
boolean requiredPermissionsGranted = PermissionsHelper
.ensureRequiredPermissions(new String[]{DANGEROUS_PERMISSION}, TESTDPC_ADMIN, mContext);
assertTrue(requiredPermissionsGranted);
assertThat(mDevicePolicyManager
.getPermissionGrantState(TESTDPC_ADMIN, mContext.getPackageName(), DANGEROUS_PERMISSION))
.isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED);
}
/**
* Saves all the restrictions.
*
* @param activity The activity.
*/
private void saveRestrictions(Activity activity) {
DevicePolicyManager devicePolicyManager
= (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
devicePolicyManager.setApplicationRestrictions(
EnforcerDeviceAdminReceiver.getComponentName(activity),
Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA, mCurrentRestrictions);
}
/** All the preparations after the provisioning procedure of system ManagedProvisioning, also shared by manual provisioning. */
@ProfileUser @WorkerThread private static void startProfileOwnerPostProvisioning(final Context context, final DevicePolicies policies) {
if (SDK_INT >= O) {
policies.execute(DevicePolicyManager::setAffiliationIds, Collections.singleton(AFFILIATION_ID));
policies.clearUserRestrictionsIfNeeded(context, UserManager.DISALLOW_BLUETOOTH_SHARING);
}
if (SDK_INT >= M) {
grantEssentialDebugPermissionsIfPossible(context);
policies.addUserRestrictionIfNeeded(context, UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
}
startDeviceAndProfileOwnerSharedPostProvisioning(context, policies);
IslandManager.ensureLegacyInstallNonMarketAppAllowed(context, policies);
disableRedundantPackageInstaller(context, policies); // To fix unexpectedly enabled package installer due to historical mistake in SystemAppsManager.
enableAdditionalForwarding(policies);
// Prepare AppLaunchShortcut
policies.addCrossProfileIntentFilter(IntentFilters.forAction(AbstractAppLaunchShortcut.ACTION_LAUNCH_CLONE).withDataSchemes("target", "package")
.withCategories(Intent.CATEGORY_DEFAULT, Intent.CATEGORY_LAUNCHER), FLAG_MANAGED_CAN_ACCESS_PARENT);
// Prepare ServiceShuttle
policies.addCrossProfileIntentFilter(new IntentFilter(ServiceShuttle.ACTION_BIND_SERVICE), FLAG_MANAGED_CAN_ACCESS_PARENT);
// Prepare API
policies.addCrossProfileIntentFilter(IntentFilters.forAction(Api.latest.ACTION_FREEZE).withDataSchemes("package", "packages"), FLAG_MANAGED_CAN_ACCESS_PARENT);
policies.addCrossProfileIntentFilter(IntentFilters.forAction(Api.latest.ACTION_UNFREEZE).withDataSchemes("package", "packages"), FLAG_MANAGED_CAN_ACCESS_PARENT);
policies.addCrossProfileIntentFilter(IntentFilters.forAction(Api.latest.ACTION_LAUNCH).withDataSchemes("package", "intent"), FLAG_MANAGED_CAN_ACCESS_PARENT);
// For Greenify (non-root automated hibernation for apps in Island)
policies.addCrossProfileIntentFilter(IntentFilters.forAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).withDataScheme("package"), FLAG_MANAGED_CAN_ACCESS_PARENT);
// Some Samsung devices default to restrict all 3rd-party cross-profile services (IMEs, accessibility and etc).
policies.execute(DevicePolicyManager::setPermittedInputMethods, null);
policies.execute(DevicePolicyManager::setPermittedAccessibilityServices, null);
if (SDK_INT >= O) policies.invoke(DevicePolicyManager::setPermittedCrossProfileNotificationListeners, null);
}
/**
* Synchronize all profile's work challenge of the given user if it's unified: tie or clear them
* depending on the parent user's secure state.
*
* When clearing tied work challenges, a pre-computed password table for profiles are required,
* since changing password for profiles requires existing password, and existing passwords can
* only be computed before the parent user's password is cleared.
*
* Strictly this is a recursive function, since setLockCredentialInternal ends up calling this
* method again on profiles. However the recursion is guaranteed to terminate as this method
* terminates when the user is a managed profile.
*/
private void synchronizeUnifiedWorkChallengeForProfiles(int userId,
Map<Integer, String> profilePasswordMap) throws RemoteException {
if (mUserManager.getUserInfo(userId).isManagedProfile()) {
return;
}
final boolean isSecure = isUserSecure(userId);
final List<UserInfo> profiles = mUserManager.getProfiles(userId);
final int size = profiles.size();
for (int i = 0; i < size; i++) {
final UserInfo profile = profiles.get(i);
if (profile.isManagedProfile()) {
final int managedUserId = profile.id;
if (mLockPatternUtils.isSeparateProfileChallengeEnabled(managedUserId)) {
continue;
}
if (isSecure) {
tieManagedProfileLockIfNecessary(managedUserId, null);
} else {
// We use cached work profile password computed before clearing the parent's
// credential, otherwise they get lost
if (profilePasswordMap != null && profilePasswordMap.containsKey(managedUserId)) {
setLockCredentialInternal(null, LockPatternUtils.CREDENTIAL_TYPE_NONE,
profilePasswordMap.get(managedUserId),
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
} else {
Slog.wtf(TAG, "clear tied profile challenges, but no password supplied.");
// Supplying null here would lead to untrusted credential change
setLockCredentialInternal(null, LockPatternUtils.CREDENTIAL_TYPE_NONE, null,
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId);
}
mStorage.removeChildProfileLock(managedUserId);
removeKeystoreProfileKey(managedUserId);
}
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(
Context.DEVICE_POLICY_SERVICE);
super.onCreate(savedInstanceState);
}
/**
* Call after {@link #notifyActivePasswordMetricsAvailable} so metrics are updated before
* reporting the password changed.
*/
private void notifyPasswordChanged(@UserIdInt int userId) {
// Same handler as notifyActivePasswordMetricsAvailable to ensure correct ordering
mHandler.post(() -> {
DevicePolicyManager dpm = (DevicePolicyManager)
mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
dpm.reportPasswordChanged(userId);
});
}
private long addEscrowToken(byte[] token, int userId) throws RemoteException {
if (DEBUG) Slog.d(TAG, "addEscrowToken: user=" + userId);
synchronized (mSpManager) {
enableSyntheticPasswordLocked();
// Migrate to synthetic password based credentials if the user has no password,
// the token can then be activated immediately.
AuthenticationToken auth = null;
if (!isUserSecure(userId)) {
if (shouldMigrateToSyntheticPasswordLocked(userId)) {
auth = initializeSyntheticPasswordLocked(null, null,
LockPatternUtils.CREDENTIAL_TYPE_NONE,
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, userId);
} else /* isSyntheticPasswordBasedCredentialLocked(userId) */ {
long pwdHandle = getSyntheticPasswordHandleLocked(userId);
auth = mSpManager.unwrapPasswordBasedSyntheticPassword(getGateKeeperService(),
pwdHandle, null, userId, null).authToken;
}
}
if (isSyntheticPasswordBasedCredentialLocked(userId)) {
disableEscrowTokenOnNonManagedDevicesIfNeeded(userId);
if (!mSpManager.hasEscrowData(userId)) {
throw new SecurityException("Escrow token is disabled on the current user");
}
}
long handle = mSpManager.createTokenBasedSyntheticPassword(token, userId);
if (auth != null) {
mSpManager.activateTokenBasedSyntheticPassword(handle, auth, userId);
}
return handle;
}
}
/**
* Start device admin activation request.
*
* @param cdmDeviceAdmin - Device admin component.
*/
private void startDeviceAdminPrompt(final ComponentName cdmDeviceAdmin) {
AlreadyRegisteredActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Intent deviceAdminIntent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
deviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cdmDeviceAdmin);
deviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
getResources().getString(R.string.device_admin_enable_alert));
startActivityForResult(deviceAdminIntent, ACTIVATION_REQUEST);
}
});
}
@TargetApi(VERSION_CODES.P)
private static Boolean isUsingUnifiedPassword(Context context) {
if (Util.SDK_INT < VERSION_CODES.P) {
return false;
}
final DevicePolicyManager dpm = context.getSystemService(DevicePolicyManager.class);
return dpm.isUsingUnifiedPassword(getComponentName(context));
}
/**
* Wipes out all the data related to this managed profile.
*/
private void removeProfile() {
Activity activity = getActivity();
if (null == activity || activity.isFinishing()) {
return;
}
DevicePolicyManager manager =
(DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
manager.wipeData(0);
// The screen turns off here
}
private void updateUi(Activity activity) {
PackageManager packageManager = activity.getPackageManager();
try {
int packageFlags;
if (Build.VERSION.SDK_INT < 24) {
//noinspection deprecation
packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
} else {
packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
}
ApplicationInfo info = packageManager.getApplicationInfo(
Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA,
packageFlags);
DevicePolicyManager devicePolicyManager =
(DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
if ((info.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
if (!devicePolicyManager.isApplicationHidden(
EnforcerDeviceAdminReceiver.getComponentName(activity),
Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA)) {
// The app is ready to enforce restrictions
// This is unlikely to happen in this sample as unhideApp() handles it.
mListener.onStatusUpdated();
} else {
// The app is installed but hidden in this profile
mTextStatus.setText(R.string.status_not_activated);
mButtonUnhide.setVisibility(View.VISIBLE);
}
} else {
// Need to reinstall the sample app
mTextStatus.setText(R.string.status_need_reinstall);
mButtonUnhide.setVisibility(View.GONE);
}
} catch (PackageManager.NameNotFoundException e) {
// Need to reinstall the sample app
mTextStatus.setText(R.string.status_need_reinstall);
mButtonUnhide.setVisibility(View.GONE);
}
}
private static boolean isDeviceEncrypted(final Context context) {
final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
if (dpm == null) return false;
final int status = dpm.getStorageEncryptionStatus();
return status == ENCRYPTION_STATUS_ACTIVE // TODO: || (SDK_INT >= N && StorageManager.isEncrypted())
|| (SDK_INT >= M && status == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cdmDeviceAdmin = new ComponentName(this, AgentDeviceAdminReceiver.class);
EnableDeviceAdminActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Intent deviceAdminIntent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
deviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cdmDeviceAdmin);
deviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
getResources().getString(R.string.device_admin_enable_alert));
startActivityForResult(deviceAdminIntent, ACTIVATION_REQUEST);
}
});
}