How to know multiple users configured in device?

邮差的信 提交于 2021-02-19 05:57:22

问题


Android 4.2 & above supports Multiple Users as described at below link...

http://developer.android.com/about/versions/android-4.2.html#MultipleUsers

Now, my questions are..

  1. Is it possible to know multiple user configured in device programmatically ? If yes, then how to get number of user configured in device ?

  2. Is it possible to get list of users ? if yes then how ?


回答1:


There is a public API to get user details but it is restricted to apps which have the "android.permission.MANAGE_USERS" permission. This permission has a protection level of "signature|system", so unless your app is installed to the system partition there is no official way to get the number of users.

I looked over the source code and came up with the following solution:

public int getNumUsers() {
    // The user directory created by android.server.pm.UserManagerService
    File userDir = new File(Environment.getDataDirectory(), "user");

    // Get the number of maximum users on this device.
    int id = Resources.getSystem()
            .getIdentifier("config_multiuserMaximumUsers", "integer", "android");
    int maxUsers;
    if (id != 0) {
        maxUsers = Resources.getSystem().getInteger(id);
    } else {
        maxUsers = 5;
    }

    int numUsers = 0;
    for (int i = 0; i <= maxUsers * 10; i += 10) {
        // If a user is created, a directory will be created under /data/user in increments
        // of 10. The first user will always be 0.
        if (new File(userDir, Integer.toString(i)).exists()) {
            numUsers++;
        }
    }

    return numUsers;
}

It has worked on the brief testing I have done but it is not used in any production code. It needs more testing but should work.


If your app had system level permissions this would be much easier:

UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
int userCount = userManager.getUserCount();


来源:https://stackoverflow.com/questions/31018677/how-to-know-multiple-users-configured-in-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!