IllegalStateException: Cannot set the device owner if the device is already set-up


I’m trying to active the device owner of my system application using hidden API
from DevicePolicyManager method dpm.setDeviceOwner(cmpName). This method is throwing illegalStateException. I also tried
Settings.Global.putInt(context.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0); and
Settings.Secure.putInt(context.getContentResolver(), Settings.Secure.USER_SETUP_COMPLETE, 0);. But android studio is still throwing an error.

Note : I have both permission in manifest <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> and <uses-permission android:name="android.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS" />


I received that error when calling dpm.setProfileOwner before dpm.setActiveAdmin; after all, a profile owner must first be an active admin. However, you’ll quickly find that, even if you issue the appropriate sequence of commands you’ll then receive the error: java.lang.IllegalStateException: Unable to set non-default profile owner post-setup.

If you check your logcat, though, I suspect you’ll also find a warning similar to one I received: avc: denied { write } for name="com.myorg.mapp-0AMhJFjDAJrJ-KmxrLiEPA==" dev="dm-3" ino=3558 scontext=u:r:system_app:s0 tcontext=u:object_r:apk_data_file:s0 tclass=dir permissive=0

This message is the key… The problem is that selinux rules prevent the apk from making changes directly to the /data/system directory, which is where the xml files (device_owner_2.xml and device_policies.xml) that define profile ownership are located.

In short, you’re out of luck. You have a few workaround options:

  • Run the dpm set-profile-owner command from within a rooted shell. Since it is run as root this will bypass selinux rules. This is a great option for quick tests
  • Grant your application root access to execute the command directly. This is a good option if you know your devices will be rooted and don’t want to have to remember the command.
  • Compile your ROM with the relevant access xml files already baked-in.

If you’re building a system app (which you must be with those permissions), you’re almost certainly rooted or building a ROM, so one of the above options should work.

Answered By – agoldencom

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published