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.