user3410367
user3410367

Reputation: 21

Can't find getUsers() method in class UserManager

How do I list all users on an Android device?

I have tried 2 approaches:

1. UserManager.getUsers()

In the android source, there seems to be a getUsers() method in the UserManager class that does exactly what I need. However, the android reference does not mention the method, and Android Studio can't resolve the method either.

Furthermore, the source shows that getUsers() returns UserInfo type (import android.content.pm.UserInfo;), but it is also not in the documentation or in Android Studio.

2. UserManager.getUserProfiles()

This method is documented in the android reference.

Create some dummy users:

adb shell pm create-user dummy1
adb shell pm create-user dummy2

Calling getUserCount() confirms there are now 3 users. However, getUserProfiles() still only returns 1 item in the list!

It's probably because a Profile is different to a User. So I tried a few variations of create-user and the following looks promising:

adb shell pm remove-user dummy1
adb shell pm remove-user dummy2
adb shell pm create-user --profileOf 0 --managed profile1
adb shell pm create-user --profileOf 0 --managed profile2

Note that profile2 couldn't be created (Error: couldn't create user.)

This time, calling getUserCount() confirms there are now 2 users. Also, getUserProfiles() confirms there are 2 items in the list. Unfortunately it seems that only one user of this type can be created, which is not useful for me as I need several additional users.

So this still doesn't answer my original question.

Solution: Reflection

getUsers() is hidden, so use reflection to access it:

Method method = um.getClass().getMethod("getUsers", null);
Object users = method.invoke(um, null);

Warning: since it's hidden, there are no guarantees the API won't change in the future.

Upvotes: 1

Views: 1497

Answers (1)

Jared Rummler
Jared Rummler

Reputation: 38121

The method is hidden with @hide. The method also requires the system permission android.Manifest.permission.MANAGE_USERS. This permission cannot be granted to third-party apps.

UserManager#getUsers() documentation:

Returns information for all users on this device, including ones marked for deletion. To retrieve only users that are alive, use getUsers(boolean).

Requires android.Manifest.permission.MANAGE_USERS permission.

Returns: the list of users that exist on the device.


How do I list all users on an Android device?

According to this answer, you could possibly use getUserProfiles.

Upvotes: 1

Related Questions