How to get a list of users for the current device,

2019-03-06 03:25发布

Background

Since API 17 (Jelly Bean), it's possible for Android users to have multiple-users using the same device. In the beginning it was only for tablets, but on Lollipop (API 21) it's available for smartphones too.

I'm trying to check out which apps the current user have that are shared amongst other users of the current device, so that I could know if the user should be notified that uninstallation can be done for all users (written about here). That's because I've made an app that can manage and uninstall apps (here).

The problem

I can't find a way to do it nicely, not even using root.

What I've tried

I thought I've found a way to do it, by using "UserManager" and "PackageManager" as such:

UserManager um=(UserManager)getSystemService(Context.USER_SERVICE);
final PackageManager packageManager=getPackageManager();
Log.d("AppLog","users count:"+um.getUserCount());
for(UserHandle userHandle : um.getUserProfiles()){
  final long serialNumberForUser=um.getSerialNumberForUser(userHandle);
  Log.d("AppLog","serial number:"+serialNumberForUser);
  final String[] packagesForUid=packageManager.getPackagesForUid((int)serialNumberForUser);
  StringBuilder sb=new StringBuilder();
  for(String packageName : packagesForUid){
    sb.append(packageName+" ");
  }
  Log.d("AppLog","packages:"+sb.toString());
}

However, it has some issues: - the function "getUserProfiles" requires API 21 and above. - the function "getPackagesForUid" requires an "int" parameter, while I have a "long" variable (from "getSerialNumberForUser"). Not sure if that's really the correct way. - Most (or all?) of the functions I've used on the "UserManager" class require a permission "MANAGE_USERS" , but apparently this is a "signature|system" permission, which isn't given so easily.

So it doesn't work, and crashes.

The question

Is there anyway to find this information? of which apps are installed for other users too?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-06 03:54

If you have root access, and Android doesn't change the directory structure again, you can enumerate the contents of /data/user/. Each subdirectory represents a user, and each second-level subdirectory represents an installed app, e.g. /data/user/0/com.example.maypp or /data/user/1/com.example.someotherapp.

查看更多
登录 后发表回答