Android UserManager: check if the user is the owner (admin)

Im developing an application with the latest version of Android (4.2.1 API level 17) for tablets with multi-user capabilities.

I want to restrict some functions (for example, access to application settings) to the tablet owner (that is, a user who can add and delete other user accounts)

is there any way to find out if the current user is the owner?

I read the UserManager and UserHandle API docs, but could not find a function that allows me to test it.

Am I missing something or is there another way to do this?

+7
source share
3 answers

Similarly, but without reflection:

static boolean isAdminUser(Context context) { UserHandle uh = Process.myUserHandle(); UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE); if(null != um) { long userSerialNumber = um.getSerialNumberForUser(uh); Log.d(TAG, "userSerialNumber = " + userSerialNumber); return 0 == userSerialNumber; } else return false; } 
+11
source

After further research, it turned out that the multi-user api does not work yet, it cannot be used for anything. there is a hack, although to check if the user is the owner using reflections:

 public boolean isCurrentUserOwner(Context context) { try { Method getUserHandle = UserManager.class.getMethod("getUserHandle"); int userHandle = (Integer) getUserHandle.invoke(context.getSystemService(Context.USER_SERVICE)); return userHandle == 0; } catch (Exception ex) { return false; } } 

This works for me on Nexus 7 and Nexus 10 with Android 4.2.1. It's very dirty. therefore, I would not recommend using it if you are not making an application with this device and version

+2
source

You can create an extension property in Kotlin to simplify it:

 val UserManager.isCurrentUserDeviceOwner: Boolean get() = if (SDK_INT >= 23) isSystemUser else if (SDK_INT >= 17) getSerialNumberForUser(Process.myUserHandle()) == 0L else true 

Then using it is as simple as the following:

 val userManager = context.getSystemService(Context.USER_SERVICE) as UserManager if (userManager.isCurrentUserDeviceOwner) TODO() else TODO() 

You can further reduce the pattern by using the global system service definitions that make userManager and other Android system services available anywhere in your Kotlin code, with the code included in this library that I made: https://github.com/LouisCAD / Splitties / tree / master / systemservices

+2
source

All Articles