Android UserManager: Check if user is owner (admin)
Asked Answered
S

3

11

Im developing an app with the latest android version (4.2.1 API-Level 17) for tablets with multiuser capabilities.

I want to restrict certain features (like the access to the app preferences) to the owner of the tablet (that is the user who can add and remove other user accounts)

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

i read through the UserManager and UserHandle API docs but couldn't find a function that allows me to check for it.

have i missed something or is there another way to do that?

Shantung answered 7/2, 2013 at 11:0 Comment(0)
W
16

Similar 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;
}
Workhouse answered 16/3, 2013 at 10:25 Comment(3)
Note: this requires minSdk 17Cob
is it also possible to check which apps are installed for which users?Regan
@JosephJohnson what is myUserHandle in this Process.myUserHandle(); ?Anthurium
A
3

You can create an extension property in Kotlin to make it simpler:

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 boilerplate by using global system services definitions that makes userManager and other Android System Services available anywhere in your Kotlin code, with code included in this library I made: https://github.com/LouisCAD/Splitties/tree/master/systemservices

Alicyclic answered 22/11, 2017 at 11:20 Comment(0)
S
2

After researching further i found out that the multiuser api is not functional yet, it cant really be used for anything. there is a hack though for checking 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 the Nexus 7 and Nexus 10 with Android 4.2.1 Its very dirty. so i wouldnt recommend using it unless you are making an app thats device and version specific

Shantung answered 7/2, 2013 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.