To execute the dpm command successfully from within the application, two conditions should be fulfilled:
- Your application must have
android.permission.MANAGE_DEVICE_ADMINS
and android.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
permissions;
- The Android setup wizard should not be completed.
To get the android.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
permission, your application must be a system app, that is, you need to set the shared user as android.uid.system
in AndroidManifest.xml
and sign the app by platform keys.
The second condition could be ignored if your app, instead of running the dpm set-device-owner
command, directly updates the system configuration XML files (since it's signed by platform keys, it is able to update them!).
Two system files should be updated. They must have the following content:
/data/system/device_owner_2.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<device-owner
package="your.package.name"
name=""
component="your.package.name/your.package.name.AdminReceiverClassName"
userRestrictionsMigrated="true"
canAccessDeviceIds="true" />
<device-owner-context userId="0" />
</root>
/data/system/device_policies.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<policies setup-complete="true" provisioning-state="3">
<admin name="your.package.name/your.package.name.AdminReceiverClassName">
<policies flags="17" />
<strong-auth-unlock-timeout value="0" />
<user-restrictions no_add_managed_profile="true" />
<default-enabled-user-restrictions>
<restriction value="no_add_managed_profile" />
</default-enabled-user-restrictions>
<cross-profile-calendar-packages />
</admin>
<password-validity value="true" />
<lock-task-features value="16" />
</policies>
To apply these changes in system configuration files, the device needs to be rebooted.
As a working sample, take a look at the source code of Headwind MDM which is the open source MDM solution able to be integrated into the AOSP (for example, LineageOS). Disclaimer: I am the owner of Headwind MDM.
The related code can be found in the following file:
app/src/main/java/com/hmdm/launcher/util/SystemUtils.java