androidandroid-sourcemdm

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" />


Solution

  • 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:

    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.