检查当前用户用户是否是owner
boolean isOwner = false;
UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
if (um != null) {
UserHandle userHandle = android.os.Process.myUserHandle();
isOwner = um.getSerialNumberForUser(userHandle) == 0;
}
检查进程是否运行在当前用户下
getCurrentUser 需要使用权限 INTERACT_ACROSS_USERS 和 MANAGE_USERS (两个都是signature|system)
boolean isCurrentUser = false;
try {
Method getUhId = UserHandle.class.getDeclaredMethod("getIdentifier");
Method getCuId = ActivityManager.class.getDeclaredMethod("getCurrentUser");
Integer myUhId = (Integer) getUhId.invoke(android.os.Process.myUserHandle());
Integer cuId = (Integer) getCuId.invoke(null);
isCurrentUser = myUhId != null && myUhId.equals(cuId);
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// ...
}
检查进程是否运行在managed profile (Android for Work)或者guest 用户中
需要权限MANAGE_USERS (signature|system)
UserManager um = UserManager.get(context);
boolean isManagedProfile = um.isManagedProfile();
boolean isGuestUser = um.isGuestUser();
反射的方法
try {
Method getUM = UserManager.class.getDeclaredMethod("get", Context.class);
Method isMP = UserManager.class.getDeclaredMethod("isManagedProfile");
Method isGU = UserManager.class.getDeclaredMethod("isGuestUser");
UserManager um = (UserManager) getUM.invoke(null, context);
Boolean isManagedProfile = (Boolean) isMP.invoke(um);
Boolean isGuestUser = (Boolean) isGU.invoke(um);
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
}
关于singleUser属性的几点说明
- 只能用于service,receivers and providers。不能用于actrivity
- 需要android.permission.INTERACT_ACROSS_USERS (system|signature)
- 需要满足以下条件之一
- appId >= 10000 (appId means base uid that stripping out the user id)
- appId 是 PHONE_UID (1001)
- 声明Declared android:persistent=”true”
- exported是false,只有在priv-app下才能是true
- 为了允许其他APP访问,需要声明android.permission.INTERACT_ACROSS_USERS_FULL (platform key signature),
System uid发送的Broadcast会忽略singleUser属性,意味这,receiver在运行中用户有不同的进程
启用multi-user 的步骤(本地测使用)
adb remount
adb shell "echo 'fw.max_users=3' >> /system/build.prop"
adb shell "echo 'fw.show_multiuserui=1' >> /system/build.prop"
adb reboot
Adding and switching users from Settings > Users