UserHandle#getUserId、Process#myUid、Process#myUserHandle的区别和联系

本文详细解析了Android系统中进程的身份标识(myUid)及其与用户标识(myUserHandle)的关系,阐述了如何通过特定算法从进程UID推导出用户ID,揭示了多用户环境下进程与用户间的映射机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Process#myUid

    /**
     * Returns the identifier of this process's uid.  This is the kernel uid
     * that the process is running under, which is the identity of its
     * app-specific sandbox.  It is different from {@link #myUserHandle} in that
     * a uid identifies a specific app sandbox in a specific user.
     */
    public static final int myUid() {
        return Os.getuid();
    }

Process#myUserHandle

/**
     * Returns this process's user handle.  This is the
     * user the process is running under.  It is distinct from
     * {@link #myUid()} in that a particular user will have multiple
     * distinct apps running under it each with their own uid.
     */
    public static UserHandle myUserHandle() {
        return UserHandle.of(UserHandle.getUserId(myUid()));
    }

UserHandle#getUserId

/**
     * @hide Range of uids allocated for a user.
     */
    public static final int PER_USER_RANGE = 100000;

/** @hide A user id constant to indicate the "system" user of the device */
public static final @UserIdInt int USER_SYSTEM = 0;



/**
     * Returns the user id for a given uid.
     * @hide
     */
    public static @UserIdInt int getUserId(int uid) {
        if (MU_ENABLED) {
            return uid / PER_USER_RANGE;
        } else {
            return UserHandle.USER_SYSTEM;
        }
    }

从上面可以知道Process#myUid返回的值有点类似Pid,就是每个进程都不一样。

而UserHandle#getUserId返回的值,就是多用户系统中代表某个用户的值。而这个值可以从Process#myUid返回值除以一个10000得到。就是说理论上,每个用户可以同时运行10000个进程。

Java Examples for android.os.UserHandle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值