获取所有用户的应用列表

For*_*vin 24 java android android-package-managers android-multiple-users android-work-profile

如果要检索当前用户的所有应用程序的ApplicationInfo列表,则可以运行:

PackageManager pkgmanager = ctx.getPackageManager();
List<ApplicationInfo> installedApps = pkgmanager.getInstalledApplications(PackageManager.GET_META_DATA);
Run Code Online (Sandbox Code Playgroud)

但我正在寻找一种获取每个用户而不只是当前用户的列表的方法。我正在处理的应用程序具有root权限!

据我了解,用户ID可以这样检索:

List<Integer> userIds = new ArrayList<>();
PackageManager pkgmanager = ctx.getPackageManager();
final UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
List<UserHandle> list = um.getUserProfiles();

for (UserHandle user : list) {
    Matcher m = p.matcher(user.toString());
    if (m.find()) {
        int id = Integer.parseInt(m.group(1));
            userIds.add(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我正在寻找这样的东西:

for (int i=0; i<userIds.size(); i++) {
    Integer userId = userIds.get(i)
    List<ApplicationInfo> installedApps = pkgmanager.getInstalledApplicationsByUserId(userId, PackageManager.GET_META_DATA);
}
Run Code Online (Sandbox Code Playgroud)

显然getInstalledApplicationsByUserId不存在。

起初我以为getPackagesForUid可以解决问题,但事实证明,Linux感觉和用户配置文件中的“用户”之间存在差异。通常,出于隔离目的,每个Android应用程序都在其自己的用户下运行。但是可以在同一用户下运行两个应用程序,以便它们可以轻松访问彼此的数据。getPackagesForUid仅返回在给定用户ID下运行的所有应用程序的名称,通常是一个。除了“用户”之外,还有“用户个人资料”,这是我希望该方法所指的内容。也许我应该也编写userProfileId而不是编写userId代码。

编辑:使用adb shell,我可以像这样检索应用程序ID:

# Get user profile IDs
USER_PROFILE_IDS="$(pm list users | grep UserInfo | cut -d '{' -f2 | cut -d ':' -f1)"

# Iterate over user profile IDs
while read -r USER_PROFILE_ID ; do
    # List the packages for each user profile by ID
    PACKAGE_IDS_FOR_THIS_USER="$(pm list packages --user "$USER_PROFILE_ID" | cut -d ':' -f2)"
    echo "#######################################################################"
    echo "The user with id $USER_PROFILE_ID has the following packages installed:"
    echo "$PACKAGE_IDS_FOR_THIS_USER"
done <<< "$USER_PROFILE_IDS"
Run Code Online (Sandbox Code Playgroud)

但这是Bash而不是Java ...

Edit2:如果我错了,请纠正我(这是我第一次用Java编写代码),但是看起来好像没有Java API可以这样做。因此,执行此操作的唯一方法是使用外壳。这就是我想出的:

import com.stericson.rootshell.RootShell;
import com.stericson.rootshell.execution.Command;
import com.stericson.rootshell.execution.Shell;
import com.stericson.roottools.RootTools;
...
public final class Api {
    ...
    /**
     * @param ctx application context (mandatory)
     * @return a list of user profile ids
     */
    private static List<Integer> getUserIds(Context ctx) {
        List<Integer> userIds = new ArrayList<>();
        PackageManager pkgmanager = ctx.getPackageManager();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //this code will be executed on devices running ICS or later
            final UserManager um = (UserManager) ctx.getSystemService(Context.USER_SERVICE);
            List<UserHandle> list = um.getUserProfiles();

            for (UserHandle user : list) {
                Matcher m = p.matcher(user.toString());
                if (m.find()) {
                    int id = Integer.parseInt(m.group(1));
                    //if (id > 0) {
                        userIds.add(id);
                    //}
                }
            }
        } else {
            userIds.add(0);
        }
        return userIds;
    }

    /**
     * @param ctx application context (mandatory)
     * @return a list of user profile ids
     */
    private static List<String> getPackageIdsByUserProfileId(Integer userId) {
        List<String> packageIds = new ArrayList<>();
        Command command = new Command(0, "pm list packages --user " + userId + " | cut -d ':' -f2 ")
        {
            @Override
            public void commandOutput(int id, String line) { 
                packageIds.add(line);
                super.commandOutput(id, line);
            }
        };
        Shell shell = RootTools.getShell(true);
        shell.add(command);

        while (!command.isFinished()) {
            Thread.sleep(100);
        }
        return packageIds;
    }
...
    /**
     * @param ctx application context (mandatory)
     * @return a list of applications
     */
    public static List<PackageInfoData> getApps(Context ctx, GetAppList appList) {
        List<Integer> userIds = getUserIds();
        for (int i=0; i<userIds.size(); i++) {
            Integer userId = userIds.get(i)
            List<String> packageIds = getPackageIdsByUserProfileId(userId)
        }
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我不知道这是否接近于实际可行的方法。除此之外,我只获得每个用户配置文件的程序包ID(“ com.whatsapp”等),但我想获得ApplicationInfo的列表,就像getInstalledApplications返回它一样。我只是想不出一个好方法来做到这一点。也许可以加载包清单,然后以某种方式基于它们创建ApplicationInfo实例?

Edit3:我想我找到pm可执行文件源代码

奇怪的是,我在其中找不到该--user标记的任何提及。

该代码最相关的部分是:

import android.os.ServiceManager;
...
mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
...
int getFlags = 0;
...
final List<PackageInfo> packages = getInstalledPackages(mPm, getFlags);
Run Code Online (Sandbox Code Playgroud)

getInstalledPackages方法mPm.getInstalledPackages然后简单地调用:

@SuppressWarnings("unchecked")
private List<PackageInfo> getInstalledPackages(IPackageManager pm, int flags)
        throws RemoteException {
    final List<PackageInfo> packageInfos = new ArrayList<PackageInfo>();
    PackageInfo lastItem = null;
    ParceledListSlice<PackageInfo> slice;
    do {
        final String lastKey = lastItem != null ? lastItem.packageName : null;
        slice = pm.getInstalledPackages(flags, lastKey);
        lastItem = slice.populateList(packageInfos, PackageInfo.CREATOR);
    } while (!slice.isLastSlice());
    return packageInfos;
}
Run Code Online (Sandbox Code Playgroud)

这给我留下了比以前更多的问题。首先,我想知道我是否只能导入com.android.commands.pm该类。其次,我想知道如何告诉它返回特定用户配置文件的软件包,或者这是否一开始就是正确的源代码。最后,我想知道我是否甚至需要root权限才能使用它。毕竟,if (Process.myUid() != ROOT_UID)检查只针对执行runRemoveProfilerunCreateProfilerunListProfiles

Edit4:我找不到该package服务的源代码。我只能找到此文件:/data/system/packages.xml。它包含有关所有软件包(针对所有用户配置文件)的一些基本软件包信息,但既不包含实际的应用程序名称,也不包含有关它们所属的用户配置文件的信息。

Edit5:我想我找到了打包服务源代码。我认为这种方法很重要:

public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId)
Run Code Online (Sandbox Code Playgroud)

不幸的是,我只是不懂代码。在我看来,这些软件包是来自mSettings.mPackages。变量在代码注释中解释如下:

{@link #mPackages}用于保护所有在内存中解析的包详细信息和其他相关状态。这是一个细粒度的锁,应仅暂时保留,因为它是系统中竞争最激烈的锁之一。

Edit6:我刚刚在该文件中找到了另一个更有趣的方法:

public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId)
Run Code Online (Sandbox Code Playgroud)

我不知道什么是ParceledListSlice,但它说<ApplicationInfo>我假设这确实接近我想要的List<ApplicationInfo>格式。但是,我仍然完全不知道如何访问该功能。

小智 4

ParceledListSlice 我在这里找到了它的代码,以及Parcelable它实现的接口代码。看起来它在内部使用某种形式的数组,因此您应该能够对其进行迭代。我实际上不能说这对您是否有帮助,因为我对这些库不太熟悉,但我希望这是一个起点。祝你好运!