繁体   English   中英

如何确定哪个用户安装了android应用程序?

[英]How to determine which user installed the android application?

使用Android 4.2及更高版本的平板电脑,可支持多个用户。 这意味着每个用户都可以拥有自己独立的应用程序集,这些应用程序将与其他用户分开。 此外,如果用户A安装了应用程序,则在用户B登录时将无法使用该应用程序。

所以我的问题是,如果在安装应用程序时有一种方法可以确定使用PackageManager ,我可以知道哪个用户实际安装了它吗?

不幸的是,没有一种简单直接的方法可以“识别”哪个用户安装了您的应用。 唯一的选择是将用户与文档中所述的唯一ID相关联:

通过在您的应用首次启动时创建新的UUID,无论用户在单个设备上安装了多少用户,您都可以获得用于跟踪每个用户的唯一ID。

因此,虽然您可能无法通过某种凭证直接检索用户,但您可以使用( 此处的代码 )模拟您自己的用户:

public class Installation {
    private static String sID = null;
    private static final String INSTALLATION = "INSTALLATION";

    public synchronized static String id(Context context) {
        if (sID == null) {  
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }

    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }
}

我找到了解决方案。 获取用户信息的最佳方法是使用UserManager API。 虽然某些API要求应用程序成为系统应用程序,但我们可以获取有关当前用户名,用户ID等的所有信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM