Skip to content

Instantly share code, notes, and snippets.

@charlieCollins
Created October 23, 2013 20:58
Show Gist options
  • Save charlieCollins/7126647 to your computer and use it in GitHub Desktop.
Save charlieCollins/7126647 to your computer and use it in GitHub Desktop.
Android Installation (unique ID per install)
public class Installation {
private static String sID;
private static final String INSTALLATION = "INSTALLATION";
// Usage: Just call Installation.id(this) from Application class onCreate and store in "session" (whatever you use for small temp in mem).
public synchronized static String id(Context context) {
if (Installation.sID == null) {
File installation = new File(context.getFilesDir(), Installation.INSTALLATION);
try {
if (!installation.exists()) {
Installation.writeInstallationFile(installation);
}
Installation.sID = Installation.readInstallationFile(installation);
} catch (Exception e) {
// fail fast
throw new RuntimeException(e);
}
}
return Installation.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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment