Question

With Android 4.2 and above in tablets, multiple users are supported. It means that each user can have his own separate set of applications which will be kept separate from other users. Also if User A installs an application, it will not be available when User B logs in.

So my question is, if there is a way to determine using PackageManager when an application gets installed, can I know which user actually installed it?

Était-ce utile?

La solution 2

I found the solution. The best way to get user information is using UserManager API. Though some API's require the application to be a system app, we can get all information about the current user name, user id etc.

Autres conseils

Unfortunately, there is not a simple and straightforward way to 'identify' which user installed your app. The only alternative is to associate a user with a unique Id as stated in the documentation:

By creating a new UUID when your app starts for the first time, you’re certain to obtain a unique ID for tracking each user, regardless of how many users install your app on a single device.

Therefore, although you may not be able to retrieve a user directly by some sort of credential, you can simulate your own with(code here):

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();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top