Skip to content

Instantly share code, notes, and snippets.

@ktuite
Created December 3, 2012 03:08
Show Gist options
  • Save ktuite/4192379 to your computer and use it in GitHub Desktop.
Save ktuite/4192379 to your computer and use it in GitHub Desktop.
Generating and storing a random, unique user id to track unique installations of an android app.
// adaptation of: http://android-developers.blogspot.com/2011/03/identifying-app-installations.html
// but using shared preferences instead of a file: http://developer.android.com/reference/android/content/SharedPreferences.html
// here's a better look at using shared preferences: http://developer.android.com/guide/topics/data/data-storage.html#pref
public class UniqueId {
private static String sID = null;
private static final String SHARED_PREF_KEY = "SKETCHABIT2";
private static final String ID_KEY = "id";
public synchronized static String id(Context context) {
if (sID == null) {
SharedPreferences pref = context.getSharedPreferences(
SHARED_PREF_KEY, 0);
sID = pref.getString(ID_KEY, "");
if (sID == "") {
sID = generateAndStoreUserId(pref);
}
}
return sID;
}
private synchronized static String generateAndStoreUserId(SharedPreferences pref) {
String id = UUID.randomUUID().toString();
SharedPreferences.Editor editor = pref.edit();
editor.putString(ID_KEY, id);
editor.commit();
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment