You can only set the device owner if there is no user account on the device, or the device is rooted. This normally means you can only set the device owner immediately after a factory reset. You can set the device owner using NFC provisioning (I've never done this) or in an adb
shell. The adb
method requires the user to enable developer mode, connect the Android device to a computer, and type a command into the shell.
Pseudocode for becoming the device owner:
if the app is not the device owner
if there is a user account
inform the user that the app cannot become the device owner
else if the app is a device administrator
instruct the user to run the adb command
else
request to become a device administrator
My Device Owner app is a complete working example, including how the command that the user must type is generated from the app's package name.