0%

Android UID

UID

Linux会为每个用户分配一个uid, 可以用id命令查看:

1
2
$ id
uid=501(sea) gid=20(staff) groups=20(staff)...

root用户uid=0

而在Android系统中, 默认情况下,Android会为新安装应用分配uid, 范围[10000, 19999], 称之为appid

通过在manifest文件中指定android:sharedUserId=""可以更改此行为, 使用相同sharedUserId的应用需要使用相同的签名, 使用相同sharedUserId的应用之间可以直接访问数据, 甚至在同一进程中运行.

支持多用户后, Android的uid由两部分组成:

uid = userid * 100_000 + appid

使用ps查看进程, 可以看到用户名形如u0_a66

1
2
3
$ ps -ef
u0_a66 11391 484 0 11:37:58 ? 00:00:00 com.android.camera
...

则该进程userid为0, appid为10066, uid为0 * 100_000 + 10066 = 10066

编程中使用android.os.Process.myUid()可以获取当前uid

UserHandle

UserHandle为对userid的封装。

使用android.os.Process.myUserHandle()可以获取当前UserHandle

UserHandle中包含一些对uid进行转换的方法:

1
2
3
4
5
public static @UserIdInt int getUserId(int uid) // uid2userid

public static @AppIdInt int getAppId(int uid) // uid2appid

public static int getUid(@UserIdInt int userId, @AppIdInt int appId) // (userid+appid)2uid

UserHandle中包含一些预定义的userid:

1
2
3
4
5
6
7
8
9
10
11
public static final @UserIdInt int USER_ALL = -1;  // 全部用户

public static final @UserIdInt int USER_CURRENT = -2; // 当前用户

public static final @UserIdInt int USER_CURRENT_OR_SELF = -3; // 当前用户或当前应用用户

public static final @UserIdInt int USER_NULL = -10000; // 未定义

public static final @UserIdInt int USER_OWNER = 0; // 系统默认用户, 已弃用

public static final @UserIdInt int USER_SYSTEM = 0; // 系统默认用户

UID System (uid=1000)

使用ps查看进程时, 可以看到名为system的用户:

1
2
3
$ ps -ef
system 19724 484 0 17:53:31 ? 00:06:57 com.android.settings:remote
...

该用户uid为1000, 开发系统应用时, 指定android:sharedUserId="android.uid.system", 并使用系统签名, 可以直接访问系统应用数据.