Friday, September 20, 2013

Android: Unique App Identifier per installation

Sometimes on Android (and probably on every other platform too ;)), it is necessary to get a unique ID in order to track the user. Yes, I agree, tracking a user is not something you should do all the time, but sometimes it is necessary – in order to identify device 2 user connections for example.

There are some methods to achieve this but nothing is really stable and tracking certain identifiers is not a good idea. This is why Google themselves came up with a good solution: don't track the device, but track the app installation. I fully agree with their post on the official Android Developers Blog.

The solution: install ID

So this is how it's done: create a helper class that creates a file containing a UUID when starting the app for the first time (or accessing the ID getter ;)). Afterwards just read that ID again and again. This way you will only lose track of the user when they de/reinstall the app but this shouldn't be a problem.
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();
    }
}
So the next time you want to track a user or app, use this code and be happy that it will definitely be a more reliable UID than some old solutions (e.g. TelephonyManager.getDeviceId(), Mac Address or ANDROID_ID ;)) – if you want a full list of them, read the Android Dev Blog.

Labels: , , , , , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home